Find the number of array occurrences more than half of the length of the array (Java implementation)

The number of times (Java implementation) More than half of the array appear

Title Description
array The number of times a number appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output.

Problem-solving ideas

There are a number of array array appearance more than half, which means the number of times it appears appearance than all the other numbers and bigger. So we can save two values in time through the array, one is the current number, a number of times that number appears. And a currently stored under the same number if the array, the times ++, or times-. If the times == 0, the next number is saved, and times set to 1. Because there is a number greater than half the number of all will be able to ensure that this is the last time the number of times is set to the number 1.
It should be noted that the results obtained in this way, does not guarantee the existence of such numbers, all need to determine whether the conclusions of this condition is satisfied, if not it shows does not exist. (Example: [1,1,1,2,2,2,3], the final result is three, but the number does not exceed 3 appears half)

Code

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int length = array.length;
        int result = array[0];
        int times = 1;
        for(int i = 1; i < length; i++) {
            if(times == 0) {
                result = array[i+1];
                times = 1;
            }
            else if(array[i] == result) {
                times++;
            }
            else if(array[i] != result) {
                times--;
            }
        }
        times = 0;
        for(int i = 0; i < length; i++) {
            if(array[i] == result) {
                times++;
            }
        }
        if(times > length/2) {
            return result;
        }
        else 
            return 0;
    }
}

Published 254 original articles · won praise 23 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_30242987/article/details/104759409