lintcode-medium-Majority Number III

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-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.

 

 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.

Challenge

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

 

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) {
        // write your code
        
        if(nums == null || nums.size() == 0 || k < 1)
            return 0;
        
        if(k == 1)
            return nums.get(0);
        
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        int size = nums.size();
        
        for(int i = 0; i < size; i++){
            int temp = nums.get(i);
            
            if(map.containsKey(temp)){
                map.put(temp, map.get(temp) + 1);
            }
            else{
                if(map.size() < k){
                    map.put(temp, 1);
                }
                else{
                    Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
                    
                    while(it.hasNext()){
                        Map.Entry<Integer, Integer> entry = it.next();
                        
                        if(entry.getValue() == 1){
                            it.remove();
                        }
                        else{
                            entry.setValue(entry.getValue() - 1);
                        }
                    }
                }
            }
            
        }
        
        int count = 0;
        int result = 0;
        
        for(Map.Entry<Integer, Integer> entry: map.entrySet()){
            int candidate = entry.getKey();
            int num = 0;
            for(int i = 0; i < size; i++)
                if(nums.get(i) == candidate)
                    num++;
            
            if(num > count){
                count = num;
                result = candidate;
            }
        }
        
        return result;
    }
}

 

以上是关于lintcode-medium-Majority Number III的主要内容,如果未能解决你的问题,请参考以下文章