-
Notifications
You must be signed in to change notification settings - Fork 0
/
majorityElement.js
52 lines (37 loc) · 1.35 KB
/
majorityElement.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const majorityElement = (nums) => {
const target = nums.length / 3
const numsCountMap = nums.reduce((numsThatAppear, num) => {
numsThatAppear[num] = numsThatAppear[num] + 1 || 1
return numsThatAppear
}, {} )
const numsThatAppear = Object.keys(numsCountMap).reduce((numsThatAppear, key) => {
const numberCount = numsCountMap[key]
return numberCount > target ? numsThatAppear.concat(key) : numsThatAppear
}, [])
return numsThatAppear
}
const majorityElement = (nums) => {
const target = nums.length / 3
const { numsThatAppear } = nums.reduce((acc, num) => {
acc.numsThatAppear[num] = acc.numsThatAppear[num] + 1 || 1
if(acc.numsThatAppear[num] > target) {
acc.numsThatAppear.add(num)
}
return acc
}, {numsCountMap: {}, numsThatAppear: new Set()} )
return Array.from(numsThatAppear)
}
const majorityElement = (nums) => {
const target = nums.length / 3
let numsCountMap = {}
let numsThatAppear = new Set()
for(let i = 0, { length } = nums; i < length; i++) {
const num = nums[i]
numsCountMap[num] = numsCountMap[num] + 1 || 1
if(numsCountMap[num] > target) {
numsThatAppear.add(num)
}
}
return Array.from(numsThatAppear)
}
export default majorityElement