(2)求衆數


求衆數

給定一個大小爲 n 的數組,找到其中的衆數。衆數是指在數組中出現次數大於 ⌊ n/2 ⌋ 的元素。

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

示例 1:

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

示例 2:

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

1、第一種解法(利用HashMap進行計數)
思路:首先利用HashMap進行計數,然後在遍歷找出value值最大的key。key即是衆數。
時間複雜度是o(n)。
代碼;

 public int majorityElement(int[] nums) {
    HashMap<Integer,Integer> map = new HashMap<>();
    for(int x:nums){
        Integer COUNT = map.get(x);
        if(map.get(x) == null)
            map.put(x, 1);
        else
            map.put(x, ++COUNT);
    }
    int max = 0;
    int rst = 0;
    for(Map.Entry<Integer,Integer> entry : map.entrySet()){
        int curr = entry.getValue();
        if(curr > max){
            max = curr;
            rst = entry.getKey();
        }

    }
    return rst;
}

2、第二種解法(摩爾投票法)
思路:首先令出現次數count=1,衆數值maj=nums[0]爲數組第一個元素。從索引1開始遍歷,之後若遇到相同的值,則 ++count。遇到不同的值則–count,如果count變成零,則maj變成maj=nums[i+1]。
時間複雜度是o(n)。
代碼:

public int majorityElement(int[] nums) {        
    int maj = nums[0];
    int count = 1;
    for(int i=1; i < nums.length; i++){
        if(maj == nums[i])
            ++count;
        else{
            --count;
            if(count == 0)
                maj = nums[i+1];
        }
    }
    return maj;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章