Majority Number III

Question

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.

Example

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

Analysis

相比于Majority Number和Majority Number II问题,该问题更加一般化。最终所需的额外空间,也就与k有关。

Solution


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> counters = new HashMap<Integer, Integer>();
        for (Integer num : nums) {
            if (!counters.containsKey(num)) {
                counters.put(num, 1);
            } else {
                counters.put(num, counters.get(num) + 1);
            }
            if (counters.size() >= k) {
                removeKey(counters);
            }
        }

        // corner case
        if (counters.size() == 0) {
            return Integer.MIN_VALUE;
        }

        // re-count the numbers
        for (Integer num : counters.keySet()) {
            counters.put(num, 0);
        }
        for (Integer num : nums) {
            if (counters.containsKey(num)) {
                counters.put(num, counters.get(num) + 1);
            }
        }

        // find majority
        int maxCounter = 0, maxKey = 0;
        for (Integer num : counters.keySet()) {
            if (counters.get(num) > maxCounter) {
                maxCounter = counters.get(num);
                maxKey = num;
            }
        }
        return maxKey;
    }

    private void removeKey(HashMap<Integer, Integer> counters) {
        Set<Integer> keySet = counters.keySet();
        List<Integer> removeList = new ArrayList<>();
        for (Integer key : keySet) {
            counters.put(key, counters.get(key) - 1);
            if (counters.get(key) == 0) {
                removeList.add(key);
            }
        }
        for (Integer key : removeList) {
            counters.remove(key);
        }
    }
}

results matching ""

    No results matching ""