【数组】229. 求众数 II (摩尔投票法)

解答:摩尔投票法
class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> res = new ArrayList<>(); if(nums.length == 0) return res; int cand1 = nums[0],cand2 = nums[0],cnt1 = 0,cnt2 = 0; for(int i = 0;i<nums.length;i++){ if(cand1 == nums[i]){ cnt1++; continue; } if(cand2 == nums[i]){ cnt2++; continue; } if(cnt1 == 0){ cand1 = nums[i]; cnt1++; continue; } if(cnt2 == 0){ cand2 = nums[i]; cnt2++; continue; } cnt1--; cnt2--; } int count1 = 0, count2 = 0; for(int num:nums){ if(cand1 == num){ count1++; } else if(cand2 == num){ count2++; } } if(count1>nums.length/3){ res.add(cand1); } if(count2>nums.length/3){ res.add(cand2); } return res; } }


浙公网安备 33010602011771号