LeetCode Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?
思路分析:這題是Majority Element的擴展,同樣可以採用Moore投票法解決。首先需要分析,如果這樣的元素(elements that appear more than ⌊ n/3 ⌋ times)存在,那麼一定不會超過兩個,證明用反證法很容易理解。接下來就是如何找出這可能的兩個元素。可以分兩步,找兩個candidate和驗證candidate出現的次數是否超過⌊ n/3 ⌋ times。 找兩個候選candidate的方法就是Moore投票法,和Majority Element中類似。需要驗證的原因是,不同於Majority Element中已經限制了主元素一定存在,這題不一定存在這樣的元素,即使存在個數也不確定,所以需要驗證過程。時間複雜度O(n),空間複雜度O(1).
AC Code:
public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        //moore voting
        //0632
        int candidate1 = 0, candidate2 = 0, times1 = 0, times2 = 0;
        int n = nums.length;
        for(int i = 0; i < n; i++){
            if(nums[i] == candidate1) {
                times1++;
            } else if(nums[i] == candidate2){
                times2++;
            } else if(times1 == 0) {
                candidate1 = nums[i];
                times1 = 1;
            } else if(times2 == 0){
                candidate2 = nums[i];
                times2 = 1;
            } else{
                times1--;times2--;
            }
        }
        
        times1 = 0; times2 = 0;
        for(int i = 0; i < n; i++){
            if(nums[i] == candidate1) times1++;
            else if(nums[i] == candidate2) times2++;
        }
        
        List<Integer> res = new ArrayList<Integer>();
        if(times1 > n/3) {
            res.add(candidate1);
        }
        if(times2 > n/3) {
            res.add(candidate2);
        }
        return res;
        //0649
    }
}


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