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.
Note
There is only one majority number in the array
Example
For [1, 2, 1, 2, 1, 3, 3] return 1
Challenge
思路:
O(n) time and O(1) space
1. 选择两个candidate
2.scan数组,如果和两个candidate相等,则相应的candidate count+1;如果不相等,两个candidate 的counter都减1(前提是counter都大于0);如果某一个counter已经等于0,那么替换candidate为当前数
3. 我们最后得到两个candidate,但是不知道谁更majority,因为一个例子就是1,1,1,1,3,3,3,2,2,2,5,5,5,最后candidate1=1, counter=1,candidate2=5,counter2=3,原因就是candidate1在之前被错误的抵消了很多。所以要再扫一遍。
public int majorityNumber(ArrayList<Integer> nums) {
int can1 = nums.get(0);
int count1 = 1;
int i = 1;
while (i < nums.size() && nums.get(i) == can1) {
count1++;
i++;
}
int can2 = 0;
int count2 = 0;
if (i < nums.size()) {
can2 = nums.get(i);
count2++;
}
while (i < nums.size()) {
int cur = nums.get(i);
if (cur == can1) {
count1++;
} else if (cur == can2) {
count2++;
} else { // not match any candidate
if (count1 == 0) {
can1 = cur;
count1++;
} else if (count2 == 0) {
can2 = cur;
count2++;
} else {
count1--;
count2--;
}
}
i++;
}
count1 = 0;
count2 = 0;
for (int j = 0; j < nums.size(); j++) {
if (nums.get(j) == can1) {
count1++;
}
if (nums.get(j) == can2) {
count2++;
}
}
return count1 > count2 ? can1 : can2;
}