[LeetCode] Majority Element - JavaScript
👩🏻💻 質問する
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.
Reference
この問題について([LeetCode] Majority Element - JavaScript), 我々は、より多くの情報をここで見つけました https://velog.io/@leeeunbin/LeetCode-Majority-Element-JavaScriptテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol