hashmap
class Solution {
public List<Integer> majorityElement(int[] nums) {
HashMap<Integer,Integer> hashmap = new HashMap<>();
int n = nums.length;
int num = n/3;
for (int i:nums){
hashmap.put(i,hashmap.getOrDefault(i,0)+1);
}
List<Integer> res = new ArrayList<>();
for(int i:hashmap.keySet()){
if(hashmap.get(i)>num){
res.add(i);
}
}
return res;
}
}
摩尔投票法
两幅动画演示摩尔投票法,最直观的理解方式 - 求众数 II - 力扣(LeetCode) (leetcode-cn.com)
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums.length==0)return res;
int sel1 = nums[0];
int sel2 = nums[0];
int count1 = 0;
int count2 = 0;
for(int num:nums){
if(sel1==num){
count1++;
continue;
}
if(sel2==num){
count2++;
continue;
}
if(count1==0){//注意是当前投票数减到0后,下一个投票如果还不为当前投票进行更换
sel1 = num;
count1++;
continue;
}
if(count2==0){//注意是当前投票数减到0后,下一个投票如果还不为当前投票进行更换
sel2 = num;
count2++;
continue;
}
count1--;
count2--;
}
count1 = 0;
count2 = 0;
for (int num : nums) {
if (sel1 == num) count1++;
else if (sel2 == num) count2++;
}
if (count1 > nums.length / 3) res.add(sel1);
if (count2 > nums.length / 3) res.add(sel2);
return res;
}
}