Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
Example
思路:将不同的元素凑对,剩下的元素则为答案。用到两两抵消的思想。
For [1, 1, 1, 1, 2, 2, 2], return 1
public int majorityNumber(int[] A){
if (A == null || A.length == 0) {
return -1;
}
int candidate = 0;
int count = 0;
for (int i = 0; i < A.length; i++) {
if (count == 0) {
candidate = A[i];
}
if (candidate == A[i]) {
count++;
} else count--;
}
return candidate;
}