题目
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于
⌊
n
/
2
⌋
⌊ n/2 ⌋
⌊n/2⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
题解:利用多数元素个数超总数一半的特点,维护当前数的cnt即可。时间O(n),空间O(1)。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
int cnt = 0,ans;
for(auto x:nums) {
if(cnt == 0) ans = x,++cnt;
else if(ans != x) --cnt;
else ++cnt;
}
return ans;
}
};