LeetCode-Majority Element II (JAVA)

Given an integer array of size n, find all elements that appear more
than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3] Output: [3] Example 2:

Input: [1,1,1,3,3,2,2,2] Output: [1,2]

題目:求解數組中數字出現次數大於n/3的數字,線性時間複雜度以及O(1)的空間

這是array類的題目中做過的最有心機的一道題,對時間的線性要求以及不能使用數字決定了這道題一定是有竅門的,這就是出現次數要大於n/3,這樣的數字如果存在的話,頂多會有兩個。
使用兩個臨時變量num1和num2作爲出現次數最多的兩個數,以及c1和c2分別記錄出現次數,第一次遍歷數組時,當num1出現是c1++,當num2出現時,c2++,都沒有出現時,c1–,c2–。這樣遍歷過一遍數組後,如果存在符合條件的數字,由於她的出現次數大於1/3,所以num1或num2中肯定會存在一個。

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> ret = new ArrayList();
        int n = nums.length;
        if(n < 1) {
             return ret;
        }
        
        
        int times = n/3;
        int num1 = nums[0];
        int num2 = nums[0];
        int c1 = 0;
        int c2 = 0;
        
        for(int i = 0; i < n ; i++) {
            if(num2 != nums[i] && (c1 == 0 || num1 == nums[i])) {
                c1++;
                num1=nums[i];
            } else if(c2 == 0 || num2 == nums[i]) {
                c2++;
                num2 = nums[i];
            } else {
                c1--;
                c2--;
            }
        }
        
        c1= 0;
        c2 = 0;
        for(int i = 0; i < n ; i++) {
            if(nums[i] == num1) {
                c1++;
            } else if(nums[i] == num2) {
                c2++;
            }
        }
        
        if(c1 > times) {
            ret.add(num1);
        }
        
        if(c2 > times ) {
            ret.add(num2);
        }
        return ret;
        
        
    }
}
發佈了51 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章