Lintcode - Majority Number III

Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. Find it.

Note

There is only one majority number in the array.

Example

For [3,1,2,3,2,3,3,4,4,4] and k = 3, return 3

Challenge

O(n) time and O(k) extra space

思路和Majority NumberII 一樣,維護k-1個candidate 在map裏面,key爲數字值,value爲出現次數。先找到這k-1個candidate後,掃描所有元素,如果該元素存在在map裏面,update map;如果不存在,1: 如果map裏面有值爲count= 0,那麼刪除掉這個元素,加入新元素;2:map裏面沒有0出現,那麼就每個元素的count--

剩下的map裏面的值都有可能是majority,所以重新掃描數組,記錄下每一個元素出現次數,次數最大的就是majority


    public int majorityNumber(ArrayList<Integer> nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int totalCan = 0;
        int i = 0;
        while (totalCan < k && i < nums.size()) {
            int cur = nums.get(i);
            if (map.containsKey(cur)) {
                map.put(cur, map.get(cur) + 1);
            } else {
                map.put(cur, 1);
                totalCan++;
            }
            i++;
        }
        while (i < nums.size()) {
            int cur = nums.get(i);
            if (map.containsKey(cur)) {
                map.put(cur, map.get(cur) + 1);
            } else { // not match any candidate
                if (map.values().contains(0)) {
                    map.put(cur, 1);
                    Integer zeroKey = null;
                    for (Map.Entry entry : map.entrySet()) {
                        if (entry.getValue().equals(0)) {
                            zeroKey = (Integer) entry.getKey();
                            break;
                        }
                    }
                    map.remove(zeroKey);
                } else {
                    for (Map.Entry entry : map.entrySet()) {
                        map.put((Integer) entry.getKey(), (Integer) entry.getValue() - 1);
                    }
                }
            }
            i++;
        }

        Map<Integer, Integer> newMap = new HashMap<Integer, Integer>();
        int maxCount = 0;
        int maxNum = 0;
        for (int j = 0; j < nums.size(); j++) {
            int cur = nums.get(j);
            if (map.containsKey(cur)) {
                newMap.put(cur, newMap.get(cur) == null ? 1 : newMap.get(cur) + 1);
                if (newMap.get(cur) > maxCount) {
                    maxCount = newMap.get(cur);
                    maxNum = cur;
                }
            }
        }
        return maxNum;
    }


發佈了172 篇原創文章 · 獲贊 1 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章