现在有一个字符串 string,它是一段英文,要求你统计这段英文里每个字母出现的次数。*
例如输入 ‘Hello’,则输出 {H:1, e:1, l:2, o:1}
1 | function count(string){ |
2 | let hash = {} |
3 | for(let i=0;i<string.length; i++){ |
4 | let letter = string[i] |
5 | if(!(letter in hash)){ |
6 | hash[letter] = 1 |
7 | }else{ |
8 | hash[letter] = hash[letter] + 1 |
9 | } |
10 | } |
11 | return hash |
12 | } |
数据结构:树。Jack 有两个儿子(Jackson1 和 Jackson2)和一个女儿(Lily),两个儿子分别有一个女儿,Lily 有一个儿子。
每个人用一个对象表示,如 {name: ‘jack’, gender: ‘male’, children: []}
1 | function createNode(name,gender, children){ |
2 | return {name: name, gender: gender, children: children || []} |
3 | } |
4 | |
5 | let root = createNode('Jack', 'male', [ |
6 | createNode('Jackson1', 'male', [ |
7 | createNode('xxx', 'female', null) |
8 | ]), |
9 | createNode('Jackson2', 'male', [ |
10 | createNode('yyy', 'female', null) |
11 | ]), |
12 | createNode('Lily', 'female', [ |
13 | createNode('zzz', 'female', null) |
14 | ]) |
15 | ]) |
了解桶排序,然后写一个桶排序函数,要求输入一个正整数数组,输出排好序的数组
1 | function sort(array){ |
2 | let hash = [] |
3 | for(let i =0;i<array.length; i++){ |
4 | let number = array[i] |
5 | if( ! (number in hash) ){ |
6 | hash[number] = 1 |
7 | }else{ |
8 | hash[number] += 1 |
9 | } |
10 | } |
11 | let result = [] |
12 | for(let i = 0; i< hash.length; i++){ |
13 | if(hash[i]){ |
14 | for(let hashIndex = 0; hashIndex < hash[i]; hashIndex ++){ // hash[i] 表示 i 出现了几次 |
15 | result.push(i) // i 就是我们要排序的数字 |
16 | } |
17 | } |
18 | } |
19 | return result |
20 | } |
21 | |
22 | sort([3,5,4,6,9,7]) // [3, 4, 5, 6, 7, 9] |