Sword refers to offer 39. Numbers that appear more than half the number of times in the array

Sword refers to offer 39. Numbers that appear more than half the number of times in the array

Title description

Insert picture description here

Problem-solving ideas

Moore vote

Insert picture description here

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        int mostNum = 0, votes = 0;

        for (int num : nums) {
    
    
            //票数为0,则选取当前的新元素为众数
            if (votes == 0) {
    
    
                mostNum = num;
                votes++;
            } else {
    
    
                //如果当前元素等于众数,则票数加1,否则减1
                votes += (num == mostNum) ? 1 : -1;
            }
        }
        return mostNum;
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115254580