一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第5天,点击查看活动详情。
题目描述
给定一个大小为 *n* 的整数数组,找出其中所有出现超过 `⌊ n/3 ⌋` 次的元素。
测试用例
示例1:
输入: [3,2,3]
输出: [3]
示例2:
输入: nums = [1]
输出: [1]
示例3:
输入: [1,1,1,3,3,2,2,2]
输出: [1,2]
算法
- 算法思路:利用摩尔投票法。摩尔投票法的基本思想很简单,在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除。这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半。如果只存在一种元素,那么这个元素则可能为目标元素。该题是摩尔投票法的简单变形。
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new LinkedList<>();
int x = 0, y = 0, cx = 0, cy = 0, count = 0;
for(int num:nums) {
if((cx == 0 || x == num) && y != num) {
cx++;
x = num;
}else if(cy == 0 || y == num) {
cy++;
y = num;
}else {
cx--;
cy--;
}
}
for(int num:nums) {
if(x == num) count++;
}
if(count > nums.length / 3) res.add(x);
count = 0;
if(x != y) {
for(int num:nums) {
if(y == num) count++;
}
if(count > nums.length / 3) res.add(y);
}
return res;
}
}