码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Majority Number III

时间:2016-03-30 06:55:21      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5335577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!