Topic description
There is a number in the array that appears more than half the length of the array, please find the number;
For example enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which is more than half the length of the array, 2 is output. If it does not exist, output 0;
Problem solving ideas
The Moore voting algorithm is used to solve this problem, and the time and space complexity of the problem can be O(n);
Use cnt to count the number of occurrences of an element. When the traversed element is not equal to the currently counted element, let cnt--;
If i elements have been searched before, but cnt == 0, it means that the first i elements have no majority, or have majority, but the number of occurrences is less than i / 2;
Because if it is more than i / 2, then cnt will not be 0. At this time, in the remaining n - i elements, the number of majorities is still more than (n - i) / 2, so continue to search to find out the majority;
public int MoreThanHalfNum_Solution(int[] array) { int majority = array[0]; for (int i = 1, cnt = 1; i < array.length; i++) { cnt = (array[i] == majority) ? cnt + 1 : cnt - 1; if (cnt == 0) { majority = array[i]; cnt = 1; } } int cnt = 0; for (int val : array) { if (val == majority) { cnt++; } } return cnt > array.length / 2 ? majority : 0; }