반응형
https://leetcode.com/problems/majority-element
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
반드시 과반수인 요소가 있으므로, 선형 시간과 O(1)의 공간으로 처리하기 위해 Boyer–Moore majority vote 알고리즘을 이용하였습니다.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int c = 1, res = nums[0];
for(int i=1; i<nums.size(); i++) {
if(c == 0) res = nums[i];
c += res == nums[i] ? 1 : -1;
}
return res;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 2149. Rearrange Array Elements by Sign (0) | 2024.02.14 |
---|---|
LeetCode 2108. Find First Palindromic String in the Array (0) | 2024.02.13 |
LeetCode 1463. Cherry Pickup II (0) | 2024.02.12 |
LeetCode 368. Largest Divisible Subset (0) | 2024.02.10 |
LeetCode 279. Perfect Squares (0) | 2024.02.08 |