https://leetcode-cn.com/problems/majority-element/
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
C++
class Solution {
public:
int majorityElement(vector<int>& nums) {
int res=nums[0];
int t=1;
for(int i=1;i<nums.size();i++){
if(nums[i]==res)t++;
else{
t--;
if(t==0)//众数数量总是大于n/2,当t=0时说明前面数组的众数等于n/2,故前面所有均可舍去,改为求i+1到n的众数
res=nums[i+1];
}
}
return res;
}
};
python
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
t=1
res=nums[0]
for i in nums:
if res==i:
++t
else:
--t
if t==0:
res=i
return res
```