腾讯五十题 No.36 多数元素

题目链接


既然个数大于一般那就先sort,再取中间吧

但是面试官可能会想要其答案

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

posted @ 2022-02-09 02:00  蹇爱黄  阅读(43)  评论(0)    收藏  举报