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
public int majorityNumber2(int[] A){
if (A == null || A.length == 0) {
return -1;
}
int candidate1 = 0;
int candidate2 = 0;
int count1 = 0;
int count2 = 0;
for (int i = 0; i < A.length; i++) {
if (count1 == 0) {
candidate1 = A[i];
}
if (count2 == 0 && A[i] != candidate1) {
candidate2 = A[i];
}
if (A[i] != candidate1 && A[i] != candidate2
&& count1 != 0 && count2 != 0) {
count1--;
count2--;
}
if (A[i] == candidate1) {
count1++;
}
if (A[i] == candidate2) {
count2++;
}
}
if (count1 > count2) {
return candidate1;
} else {
return candidate2;
}
}