leetcode刷題-169.Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:
Input: [3,2,3]
Output: 3

Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2

思路

求衆數,而且這個衆數出現次數超過一半,所以就用大衆化的方法,用map記錄每個數字出現的次數,然後找到超過一半的,時間複雜度O(n),空間複雜度O(n)

代碼
class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        
        for (int key : map.keySet()) {
            if (map.get(key) > nums.length / 2) {
                return key;
            }
        }
        
        return -1;
    }
}

之後看了題解的優質解答,摩爾投票法
基本思想:尋找數組中超過一半的數字,這意味着數組中其他數字出現次數的總和都是比不上這個數字出現的次數
即如果把 該衆數記爲 +1 ,把其他數記爲 −1 ,將它們全部加起來,和是大於 0 的。
所以可以這樣操作:

  • 設置兩個變量 candidate 和 count,candidate 用來保存數組中遍歷到的某個數字,count
    表示當前數字的出現次數,一開始 candidate 保存爲數組中的第一個數字,count 爲 1
  • 遍歷整個數組
  • 如果數字與之前 candidate 保存的數字相同,則 count 加 1
  • 如果數字與之前 candidate 保存的數字不同,則 count 減 1
  • 如果出現次數 count 變爲 0 ,candidate 進行變化,保存爲當前遍歷的那個數字,並且同時把 count 重置爲 1
  • 遍歷完數組中的所有數字即可得到結果

時間複雜度O(n),空間複雜度O(1)

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