题目
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
代码
Python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# 摩尔投票法:核心理念为 “正负抵消” ;时间和空间复杂度分别为O(N)和O(1)
cnt=0
for num in nums:
if cnt==0: res=num # 更新众数
cnt+=1 if res==num else -1 # 与众数相同加1,不同减1
return res
C++
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt=0, res;
for (auto num:nums) { // 自动遍历容器中所有元素
if (cnt==0) res=num,cnt=1;
else {
if (res==num) cnt++;
else cnt--;
}
}
return res;
}
};