forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0169-majority-element.js
47 lines (40 loc) · 957 Bytes
/
0169-majority-element.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
/**
* Boyer Moore Algorithm
* Time O(N) | Space O(1)
* https://leetcode.com/problems/majority-element
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
let res = nums[0];
let count = 1;
for (let i = 1; i < nums.length - 1; i++) {
if (nums[i] === res) count++;
else if (!--count) {
res = nums[i + 1];
count = 0;
}
}
return res;
};
/**
* HashMap
* Time O(N) | Space O(N)
* https://leetcode.com/problems/majority-element
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
const occuranceOfElement = new Map();
for (let i = 0; i < nums.length; i++) {
if (occuranceOfElement.has(nums[i])) {
let occurance = occuranceOfElement.get(nums[i]);
occuranceOfElement.set(nums[i], occurance + 1);
} else {
occuranceOfElement.set(nums[i], 1);
}
}
for (let [key, value] of occuranceOfElement) {
if (value > nums.length / 2) return key;
}
};