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.

找出數組中元素個數超過n/3的元素。

解題思路: 忘了在哪看見過這個的數學證明,數組中超過n/3的元素個數最多兩個,本題用摩爾投票法,需要兩輪計數。

                    第一輪:找出出現次數最多的兩個元素,每次存儲兩個元素n1和n2,如果第三個元素與其中一個相同,則增加計數cn1或cn2,  否則,清除n1和n2,從下一個數據開始重新統計.

                   經過第一輪查找數目較多的元素一定可以被查到,當然查到的不一定是大於n/3的。所以第二輪就驗證這兩個元素是否滿足條件,即出現的次數是否大於n/3;

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
       List<Integer> res = new ArrayList<Integer>();
        if (nums == null || nums.length == 0) return res;
        if (nums.length == 1) {
			res.add(nums[0]);
			return res;
		}
        int n1 = 0, n2 = 0, cn1 = 0, cn2 = 0;
        for (int i = 0; i < nums.length; i++) {
			if (nums[i] == n1) {
				cn1++;
			}else if (nums[i] == n2) {
				cn2++;
			}else if (cn1 == 0) {
				n1 = nums[i];
				cn1++;
			}else if (cn2 == 0) {
				n2 = nums[i];
				cn2++;
			}else {
				cn1--;
				cn2--;
			}
		}
        cn1 = 0; cn2 = 0;
        for (int i = 0; i < nums.length; i++) {
			if (n1 == nums[i]) {
				++cn1;
			}else if (n2 == nums[i]) {
				++cn2;
			}
		}
        if (cn1 > nums.length/3) res.add(n1);
        if (cn2 > nums.length/3) res.add(n2);
        return res;
     
    }
}



發佈了97 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章