LeetCode169.多元素(Java实现)

class Solution169 {
    public int majorityElement(int[] nums) {
        //不使用排序 在O(n)解决
        int m=nums[0];
        int count=1;
        for(int i=1;i<nums.length;i++){
            if(nums[i]==m){
                count++;
            }else{
                count--;
                if(count==0){
                    m=nums[i];
                    count=1;
                }
            }
        }
        return m;

    }
}
发布了31 篇原创文章 · 获赞 1 · 访问量 1265

猜你喜欢

转载自blog.csdn.net/qq_45824565/article/details/104460872