[Sword Finger OFFER] Interview Question 39. Numbers that appear more than half of the time in the array

Question : The number of occurrences of a number in the array exceeds half the length of the array. Please find out this number.

You can assume that the array is non-empty, and there will always be a majority of elements in a given array.

Example 1:

Input: [1, 2, 3, 2, 2, 2, 5, 4, 2]
Output: 2

limit:

1 <= array length <= 50000

Answer :

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        int count = 1, num = nums[0];
        for(int i = 1; i < nums.length; i++){
    
    
            if(nums[i] == num){
    
    
                count++;
            }else if(count > 0){
    
    
                count--;
            }else if(count == 0){
    
    
                count = 1;
                num = nums[i];
            }
        }
        return num;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44485744/article/details/105876539