Majority Element
Thoughts
Code
/*
* @lc app=leetcode id=169 lang=cpp
*
* [169] Majority Element
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
const int N = nums.size();
if (N == 1) return nums[0];
if (N == 0) return 0;
int count = 1, target = nums[0];
for (int i = 1; i < N; ++i) {
if (target != nums[i]) --count;
else ++count;
if (count < 0) {
target = nums[i];
count = 0;
}
}
return target;
}
};
Analysis
Last updated