天天看點

求衆數(Java實作)

題目:

給定一個大小為 n 的數組,找到其中的衆數。衆數是指在數組中出現次數大于 

⌊ n/2 ⌋

 的元素。

你可以假設數組是非空的,并且給定的數組總是存在衆數。

示例 1:

輸入: [3,2,3]
輸出: 3      

示例 2:

輸入: [2,2,1,1,1,2,2]
輸出: 2

代碼如下:
      
class Solution {
    public int majorityElement(int[] nums) {
        int len = nums.length;
        int count = 0;
        int max = nums[0];
        
        for(int i = 1; i < len; i++){
           if(max == nums[i]){
                count++;
           }else{
                count--;
               if(count == 0){
                    max = nums[i];
                   count++;
               }
           }
        }
        return max;
    }
}