Majority Number II
原題鏈接: http://lintcode.com/en/problem/majority-number-ii/#
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.
There is only one majority number in the array
For [1, 2, 1, 2, 1, 3, 3] return 1
O(n) time and O(1) space
SOLUTION 1:
與Majority Number 1相似。但我們要保存2個number.
1. 遇到第一個不同的值,先記錄number 2.
2. 新值與n1,n2都不同,則cnt1,cnt2都減少
3. 當n1,n2任意一個為0時,從新值中挑出一個記錄下來。
4. 最后再對2個候選值進行查驗,得出最終的解。
主頁君其實也想不太明白這個題目為什么這樣解。
還是舉個例子吧
7 1 7 7 61 61 61 10 10 10 61
n1 7 7 7 7 7 7 7 7 7 10 10
cnt1 1 1 2 3 2 2 2 1 0 1 1
n2 0 1 1 1 1 61 61 61 61 61 61
cnt2 0 1 1 1 0 1 2 1 0 0 1
證明:
1. 我們對cnt1,cnt2減數時,相當於丟棄了3個數字(當前數字,n1, n2)。也就是說,每一次丟棄數字,我們是丟棄3個不同的數字。
而Majority number超過了1/3所以它最后一定會留下來。
設定總數為N, majority number次數為m。丟棄的次數是x。則majority 被扔的次數是x
而m > N/3, N - 3x > 0.
3m > N, N > 3x 所以 3m > 3x, m > x 也就是說 m一定沒有被扔完
最壞的情況,Majority number每次都被扔掉了,但它一定會在n1,n2中。
2. 為什么最后要再檢查2個數字呢?因為數字的編排可以讓majority 數被過度消耗,使其計數反而小於n2,或者等於n2.前面舉的例子即是。
另一個例子:
1 1 1 1 2 3 2 3 4 4 4 這個 1就會被消耗過多,最后余下的反而比4少。

1 public class Solution { 2 /** 3 * @param nums: A list of integers 4 * @return: The majority number that occurs more than 1/3 5 */ 6 public int majorityNumber(ArrayList<Integer> nums) { 7 // write your code 8 // When there are only 1 or 2 elements in the array, 9 // there is no solution. 10 if (nums == null || nums.size() <= 2) { 11 return -1; 12 } 13 14 int n1 = 0; 15 int n2 = 0; 16 17 int cnt1 = 0; 18 int cnt2 = 0; 19 20 int size = nums.size(); 21 for (int i = 0; i < size; i++) { 22 int num = nums.get(i); 23 if (cnt1 != 0 && num == n1) { 24 cnt1++; 25 } else if (cnt2 != 0 && num == n2) { 26 cnt2++; 27 } else if (cnt1 == 0) { 28 cnt1 = 1; 29 n1 = num; 30 } else if (cnt2 == 0) { 31 cnt2 = 1; 32 n2 = num; 33 } else { 34 cnt1--; 35 cnt2--; 36 } 37 } 38 39 // count the two candiates. 40 cnt1 = 0; 41 cnt2 = 0; 42 for (int num: nums) { 43 if (num == n1) { 44 cnt1++; 45 } else if (num == n2) { 46 cnt2++; 47 } 48 } 49 50 if (cnt1 < cnt2) { 51 return n2; 52 } 53 54 return n1; 55 } 56 }
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/math/MajorityNumber2.java