题目
数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
解题思路
题目要求时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案
投票算法 + 验证是否存在"主要元素"
- 投票算法
- 统计candidate数量
- count(candidate) > nums.length / 2,candidate即为"主要元素"
- 否则不存在"主要元素"
代码
class Solution {
public int majorityElement(int[] nums) {
Integer candidate = null;
int count = 0;
// 投票算法
for (int n : nums) {
if (count == 0) candidate = n;
count += candidate == n ? 1 : -1;
}
// 验证是否存在主要元素
// count(candidate) > nums.length / 2则存在;否则不存在
count = 0;
for (int n : nums) if (n == candidate) count++;
return count > nums.length / 2 ? candidate : -1;
}
}