|
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 | + */ |
3 | 8 |
|
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; |
15 | 12 |
|
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 | + } |
19 | 20 |
|
| 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 | + } |
20 | 47 | };
|
0 commit comments