Algorithmic questions: analysis of more than half of the numerical questions in the array

Title description

There is a number in the array that appears more than half the length of the array. Please find out this number. For example, enter an array {1,2,3,2,2,2,5,4,2} of length 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.

Topic analysis

Since there is a certain number a, which accounts for more than half of the array, if the number a and other numbers cancel each other, at least one number a can be left, so you can use this method: remember the first number first, and initialize a count , If it is traversed later, if it is the same number, it will increase the count (the same number is superimposed), if it is different, the count will decrease (different numbers cancel each other out). Such as:
1,2,3,2,2,2,5,4,2
1: First remember 1, count = 1
2: Not the same as the remembered 1, count is less than 0, discard the remembered 1
3: Re-remember 3, count = 1
2: Discard 3, count = 0
2: Remember 2, count = 1
2: Same as remembered, count = 2
5: Not the same, count = 1
4: Not the same , Count = 0, discard 2
2: Re-remember 2, count = 1,
so you get 2

If count = 0, it means that no number is more than half, and there must be no answer.
If count = 1, there may be an answer, because different numbers will cancel each other out, and the number obtained is not necessarily more than half, such as: 1, 2, 3, 4, 5 will get 5, but 5 is not an answer that satisfies the requirements.
At this time, just return the obtained number to the array and check it again to see if the number meets the requirements.
The time complexity of the entire algorithm is o(n)

Code

public int MoreThanHalfNum_Solution(int [] array) {
        if(array == null || array.length == 0){
            return 0;
        }
        int count = 0;
        int num = -1;//-1 不指向任何数
        for (int i = 0; i < array.length; i++) {
            if(array[i] == num){
                count++;
            } else if(num == -1){ //重新指向一个
                num = array[i];
                count++;
            } else{
                count--;
                if(count == 0){ //消除指向
                    num = -1;
                }
            }
        }
        if(count == 0) { //count == 0,一定没有满足要求的
            return 0;
        } else { //可能有,需要对num精确检查
            int numCount = 0;
            for (int i : array) {
                if(i == num)
                    numCount++;
            }
            if(numCount > array.length/2)
                return num;
            else
                return 0;
        }
    }

Guess you like

Origin blog.csdn.net/Baibair/article/details/108564642