1、描述
数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
来源:力扣(LeetCode)
链接:
2、关键字
众数、数组。
3、思路
出现的次数>一半
4、notes
投票法
5、复杂度
时间:O(N)2次数组长度的遍历,2n
空间:O(N)有可能需要n/2+1的空间,如果只有一种数字,空间就是n,
6、code
class Solution {
public:
int majorityElement(vector<int>& nums) {
int res = nums[0];
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if (res == nums[i]) {
count++;
}else {
count--;
if(count < 0){ // 这里应该写< 0,而不是==0
res = nums[i];
count = 1;
}
}
}
return res;
}
};