Title description
The number of occurrences of a number in the array exceeds half of the length of the array. Please find out this number. For example, enter an array {1,2,3,2,2,2,5,4,2} with a length of 9. Since the number 2 appears 5 times in the array, which is more than half the length of the array, 2 is output. If it does not exist, output 0.
Example 1
enter
[1,2,3,2,2,2,5,4,2]
return value
2
Idea :
Compare the number count+1 that appears for the first time with the subsequent numbers. If it is equal, then +1, otherwise -1,
and finally check whether it exceeds half of the length.
Code implementation :
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int count = 0;
int flag = 0;
for (int num : array) {
if (count == 0) {
flag = num;
}
count += (flag == num) ? 1 : -1;
}
count = 0;
for (int num : array) {
if (num == flag) {
count++;
}
}
return (count * 2 > array.length) ? flag : 0;
}
}