-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMajority Element.js
42 lines (33 loc) · 1.01 KB
/
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
/*
169. Majority Element
https://leetcode.com/problems/majority-element/
*/
/* TIME COMPLEXITY O(N) */
/*
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
*/
var majorityElement = function (nums) {
var map = new Map(); //Create A New HashMap
console.log(map);
for (let i = 0; i < nums.length; i++) { // 0 - nums.length value
if (map.has(nums[i])) { //Check Array Single Element Present in Map or not
map.set(nums[i], map.get(nums[i]) + 1); //If Element present in Map than increment key:value number By One
}
else {
map.set(nums[i], 1); //If the element not present in map than add into the map
}
}
console.log(map);
let max = Math.max(...map.values()); // Find the maximum value in map
for (var [key, value] of map.entries()) { // Check Max Value Key
if (max == value) {
return key;
}
}
};
console.log(majorityElement([3, 2, 3, 4, 5, 4, 4]));