Skip to content

Commit 4077d1f

Browse files
Merge pull request #3002 from aestheticw3/patch-5
Update 0169-majority-element.js
2 parents 6d85365 + 0d2c876 commit 4077d1f

File tree

1 file changed

+43
-16
lines changed

1 file changed

+43
-16
lines changed

Diff for: javascript/0169-majority-element.js

+43-16
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,47 @@
1-
// problem link https://leetcode.com/problems/majority-element
2-
// time complexity O(n)
1+
/**
2+
* Boyer Moore Algorithm
3+
* Time O(N) | Space O(1)
4+
* https://leetcode.com/problems/majority-element
5+
* @param {number[]} nums
6+
* @return {number}
7+
*/
38

4-
var majorityElement = function(nums) {
5-
6-
const occuranceOfElement = new Map();
7-
for(let i = 0; i < nums.length; i++) {
8-
if(occuranceOfElement.has(nums[i])) {
9-
let occurance = occuranceOfElement.get(nums[i]);
10-
occuranceOfElement.set(nums[i], occurance+1);
11-
} else {
12-
occuranceOfElement.set(nums[i], 1);
13-
}
14-
}
9+
var majorityElement = function (nums) {
10+
let res = nums[0];
11+
let count = 1;
1512

16-
for(let [key,value] of occuranceOfElement) {
17-
if(value > nums.length / 2) return key;
18-
}
13+
for (let i = 1; i < nums.length - 1; i++) {
14+
if (nums[i] === res) count++;
15+
else if (!--count) {
16+
res = nums[i + 1];
17+
count = 0;
18+
}
19+
}
1920

21+
return res;
22+
};
23+
24+
/**
25+
* HashMap
26+
* Time O(N) | Space O(N)
27+
* https://leetcode.com/problems/majority-element
28+
* @param {number[]} nums
29+
* @return {number}
30+
*/
31+
32+
var majorityElement = function (nums) {
33+
const occuranceOfElement = new Map();
34+
35+
for (let i = 0; i < nums.length; i++) {
36+
if (occuranceOfElement.has(nums[i])) {
37+
let occurance = occuranceOfElement.get(nums[i]);
38+
occuranceOfElement.set(nums[i], occurance + 1);
39+
} else {
40+
occuranceOfElement.set(nums[i], 1);
41+
}
42+
}
43+
44+
for (let [key, value] of occuranceOfElement) {
45+
if (value > nums.length / 2) return key;
46+
}
2047
};

0 commit comments

Comments
 (0)