演算法:Majority Element(求眾數)

架構師易筋發表於2019-02-21

說明

演算法:Majority Element
LeetCode地址:https://leetcode.com/problems/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

解題思路

題意是從陣列中找出出現次數最多的數,而且最多的數大於一半 ⌊ n/2 ⌋,步驟如下:
1. 如果陣列只有一個數直接返回第一個數,
2. 用HashMap儲存key為出現的數字,value為出現次數
3. 跟已經儲存的最大出現次數比較,如果大於,則儲存最大出現次數,和該數字。
4. 時間複雜度為O(n)

程式碼實現

import java.util.HashMap;
import java.util.Map;

public class MajorityElement {

    public int majorityElement(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }

        int majorityKey = 0;
        int majorityCount = 0;

        Map<Integer, Integer> numCountMap = new HashMap<>();
        for (int num: nums) {
            if (numCountMap.containsKey(num)) {
                numCountMap.put(num, numCountMap.get(num) + 1);
                if (numCountMap.get(num) > majorityCount) {
                    majorityCount = numCountMap.get(num);
                    majorityKey = num;
                }
            } else  {
                numCountMap.put(num, 1);
            }
        }

        return majorityKey;
    }

    public static void main(String[] args) {
        int[] inputNums = {2,2,1,1,1,2,2};
        System.out.println("Output: " + new MajorityElement().majorityElement(inputNums));
    }
}


結果輸出

Output: 2

程式碼執行效率

Runtime: 25 ms, faster than 19.42% of Java online submissions for Majority Element.
Memory Usage: 43.4 MB, less than 20.42% of Java online submissions for Majority Element.

總結

實為考察重複數字出現, 時間複雜度為O(n)。注意:儲存最大資料的時候,考慮只有一個數的情況,只有一個數就沒有比較,也就是初始資料。

程式碼下載:
https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/MajorityElement.java

相關文章