LeetCode #169 Majority Element
var majorityElement = function(nums) {
if(nums.length === 1) return nums[0];
let answer = 0;
let temp = 0;
let map = new Map();
for(let x of nums) {
if(!map.get(x)) {
map.set(x, 1);
} else {
map.set(x, map.get(x) + 1);
}
}
for(let [key, val] of map) {
if(temp < val) {
temp = val;
answer = key;
}
}
return answer;
};
// 다른 분의 풀이
var majorityElement = function(nums) {
// sort the array and the middle is the majority
nums.sort((a, b) => a - b);
return nums[Math.floor(nums.length / 2)];
};
문제 설명을 그냥 읽지 말자..........
The majority element is the element that appears more than ⌊n / 2⌋ times.