1. 程式人生 > 其它 >Majority Number III

Majority Number III

Source

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.

Example
Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3.

Note
There is only one majority number in the array.

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

題解

Majority Number II的升級版,有了前兩道題的鋪墊,此題的思路已十分明瞭,對 K-1個數進行相互抵消,這裡不太可能使用 key1, key2...等變數,用陣列使用上不太方便,且增刪效率不高,故使用雜湊表較為合適,當雜湊表的鍵值數等於 K 時即進行清理,當然更準備地來講應該是等於 K-1時清理。故此題的邏輯即為:

1. 更新雜湊表,若遇雜湊表 size == K 時則執行刪除操作,

2. 最後遍歷雜湊表取真實計數器值,返回最大的 key.

Java

public class Solution {
    /**
     * @param nums: A list of integers
     * 
@param k: As described * @return: The majority number */ public int majorityNumber(ArrayList<Integer> nums, int k) { HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); if (nums == null || nums.isEmpty()) return -1; // update HashMap
for (int num : nums) { if (!hash.containsKey(num)) { hash.put(num, 1); if (hash.size() >= k) { removeZeroCount(hash); } } else { hash.put(num, hash.get(num) + 1); } } // reset for (int key : hash.keySet()) { hash.put(key, 0); } for (int key : nums) { if (hash.containsKey(key)) { hash.put(key, hash.get(key) + 1); } } // find max int maxKey = -1, maxCount = 0; for (int key : hash.keySet()) { if (hash.get(key) > maxCount) { maxKey = key; maxCount = hash.get(key); } } return maxKey; } private void removeZeroCount(HashMap<Integer, Integer> hash) { Set<Integer> keySet = hash.keySet(); for (int key : keySet) { hash.put(key, hash.get(key) - 1); } /* solution 1 */ Iterator<Map.Entry<Integer, Integer>> it = hash.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, Integer> entry = it.next(); if(entry.getValue() == 0) { it.remove(); } } /* solution 2 */ // List<Integer> removeList = new ArrayList<>(); // for (int key : keySet) { // hash.put(key, hash.get(key) - 1); // if (hash.get(key) == 0) { // removeList.add(key); // } // } // for (Integer key : removeList) { // hash.remove(key); // } /* solution3 lambda expression for Java8 */ } }

原始碼分析

此題的思路不算很難,但是實現起來還是有點難度的,Java 中刪除雜湊表時需要考慮執行緒安全。

複雜度分析

時間複雜度 O(n), 使用了雜湊表,空間複雜度 O(k).