0
点赞
收藏
分享

微信扫一扫

LeetCode日记 229.求众数II

phpworkerman 2023-01-21 阅读 54


题目来源:https://leetcode-cn.com/problems/majority-element/

LeetCode日记  229.求众数II_List

class Solution {
public List<Integer> majorityElement(int[] nums) {
if(nums == null||nums.length == 0){
return new ArrayList();
}
int res1 = nums[0];
int res2 = nums[0];
int count1 = 0;
int count2 = 0;
int n = nums.length;
ArrayList<Integer> ans = new ArrayList();
for(int i = 0;i<nums.length;i++){
if(nums[i] == res1){
count1++;
continue;
}
if(nums[i] == res2){
count2++;
continue;
}

if(count1 == 0){
res1 = nums[i];
count1 = 1;
continue;
}
if(count2 == 0){
res2 = nums[i];
count2 = 1;
continue;
}
count1--;
count2--;

}
count1 = 0;
count2 = 0;
for(int num:nums){
if(num==res1){
count1++;
}else if(num==res2){
count2++;
}
}
if(count1>n/3){
ans.add(res1);
}
if(res2!=res1&&count2>n/3){
ans.add(res2);
}


return ans;
}
}


举报

相关推荐

0 条评论