Lintcode - 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.

Note

There is only one majority number in the array.

Example

For [3,1,2,3,2,3,3,4,4,4] and k = 3, return 3

Challenge

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

思路和Majority NumberII 一样,维护k-1个candidate 在map里面,key为数字值,value为出现次数。先找到这k-1个candidate后,扫描所有元素,如果该元素存在在map里面,update map;如果不存在,1: 如果map里面有值为count= 0,那么删除掉这个元素,加入新元素;2:map里面没有0出现,那么就每个元素的count--

剩下的map里面的值都有可能是majority,所以重新扫描数组,记录下每一个元素出现次数,次数最大的就是majority


    public int majorityNumber(ArrayList<Integer> nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int totalCan = 0;
        int i = 0;
        while (totalCan < k && i < nums.size()) {
            int cur = nums.get(i);
            if (map.containsKey(cur)) {
                map.put(cur, map.get(cur) + 1);
            } else {
                map.put(cur, 1);
                totalCan++;
            }
            i++;
        }
        while (i < nums.size()) {
            int cur = nums.get(i);
            if (map.containsKey(cur)) {
                map.put(cur, map.get(cur) + 1);
            } else { // not match any candidate
                if (map.values().contains(0)) {
                    map.put(cur, 1);
                    Integer zeroKey = null;
                    for (Map.Entry entry : map.entrySet()) {
                        if (entry.getValue().equals(0)) {
                            zeroKey = (Integer) entry.getKey();
                            break;
                        }
                    }
                    map.remove(zeroKey);
                } else {
                    for (Map.Entry entry : map.entrySet()) {
                        map.put((Integer) entry.getKey(), (Integer) entry.getValue() - 1);
                    }
                }
            }
            i++;
        }

        Map<Integer, Integer> newMap = new HashMap<Integer, Integer>();
        int maxCount = 0;
        int maxNum = 0;
        for (int j = 0; j < nums.size(); j++) {
            int cur = nums.get(j);
            if (map.containsKey(cur)) {
                newMap.put(cur, newMap.get(cur) == null ? 1 : newMap.get(cur) + 1);
                if (newMap.get(cur) > maxCount) {
                    maxCount = newMap.get(cur);
                    maxNum = cur;
                }
            }
        }
        return maxNum;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值