Lintcode: Majority Number II 解题报告
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
posted on 2014-12-20 19:42 Yu's Garden 阅读(3174) 评论(1) 编辑 收藏 举报