06.27.2024
1. Problem
2. My Code
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
var obj = Object();
nums.forEach((e) => {
if (obj[e]) obj[e]++;
else obj[e] = 1;
});
let max = 0;
Object.entries(obj).forEach((pair) => {
const standard = parseInt(nums.length / 2);
if (pair[1] > standard) max = pair[0];
});
return max;
};
3. For Follow-Up
Though I haven't tried this problem with the follow-up rule, you can use Boyer-Moore Majority Vote algorithm.
I am not sure of the popularity or the necessity of this algorithm but just in case anyone wants to try, you can search for it.
'CS > algorithm' 카테고리의 다른 글
[LeetCode] 26. Remove Duplicates from Sorted Array (0) | 2024.06.28 |
---|---|
[LeetCode] 78. Subsets (0) | 2024.01.29 |
[LeetCode] 446. Arithmetic Slices II - Subsequence (0) | 2024.01.08 |
[LeetCode] 46. Permutations (0) | 2024.01.03 |
1912 연속합 with 파이썬 (feat. DP, 동적 프로그래밍) (0) | 2023.08.18 |