leetcode 229摩爾選舉法

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        int cnt1=0.cnt2=0,a=0,b=0;
        List<Integer> res=new ArrayList<>();
        int n=nums.length;

        for (int num : nums) {
         	if(a==num) cnt1++;
         	else if(b==num) cnt2++;
         	else if(cnt1==0) {a=num;cnt1=1;}
         	else if(cnt2==0) {b=num;cnt2=1} 
         	else
         	{
         		cnt1--;
         		cnt2--;
         	}
         }

         cnt1=0;cnt2=0;
         for(int num : nums)
         {
         	if(num==a) cnt1++;
         	else if(num==b) cnt2++;
         } 
         if(cnt1>n/3) res.add(a);
         if(cnt2>n/3) res.add(b);
         return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章