Java实现找出数组中出现次数超过一半的数 -----(笔记)

Java实现找出数组中出现次数超过一半的数 -----(笔记)

public class Test {
    
    
    public int majorityElement(int[] nums) {
    
    
        int count = 0;
        int candidate = 0;
        for(int n : nums){
    
    
            if(count == 0) candidate = n;
            if(candidate == n){
    
    
                count++;
            }else{
    
    
                count--;
            }
        }
        return candidate;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41454682/article/details/113108325