forked from paopao2/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Majority Element II.js
59 lines (50 loc) · 1.26 KB
/
Majority Element II.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
53
54
55
56
57
58
59
/**
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Hint:
How many majority elements could it possibly have?
*/
/**
* @param {number[]} nums
* @return {number[]}
*/
var majorityElement = function(nums) {
var len = nums.length,
candidate1,
count1 = 0,
candidate2,
count2 = 0,
result = [],
i;
for (i = 0; i < len; i++) {
if (nums[i] === candidate1) {
count1++;
} else if (nums[i] === candidate2) {
count2++;
} else if (count1 === 0) {
count1++;
candidate1 = nums[i];
} else if (count2 === 0) {
count2++;
candidate2 = nums[i];
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (i = 0; i < len; i++) {
if (nums[i] === candidate1) {
count1++;
} else if (nums[i] === candidate2) {
count2++;
}
}
if (count1 > Math.floor(len / 3)) {
result.push(candidate1);
}
if (count2 > Math.floor(len / 3)) {
result.push(candidate2);
}
return result;
};