Majority Number III (主元素 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.

Notice

There is only one majority number in the array.
Example
Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3.

分析

请参阅 Majority Number

代码

public class Solution {
    /**
     * @param nums: A list of integers
     * @param k: As described
     * @return: The majority number
     */
    public int majorityNumber(ArrayList nums, int k) {
        // write your code
        Map map = new HashMap();
        int max = nums.size() / k;
        for (int i : nums) {
            int count = 1;
            if (map.containsKey(i)) {
                count = map.get(i) + 1;
            }
            map.put(i, count);
            if (map.keySet().size() > k) {
                System.out.println(map.keySet().size());
                removeOne(map);
                System.out.println(map.keySet().size());
            }
        }
        for (int i : map.keySet()) {
            map.put(i, 0);
        }
        for (int i : nums) {
            if (map.containsKey(i)) {
                int count = map.get(i) + 1;
                if (count > max) {
                    return i;
                }
                map.put(i, count);
            }
        }
        return 0;
    }
    private void removeOne(Map map){
        Iterator iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            int temp=iterator.next();
            int count=map.get(temp);
            count--;
            if(count==0){
                iterator.remove();
            }else{
                map.put(temp,count);
            }
        }
    }
}

你可能感兴趣的:(Majority Number III (主元素 III))