代码面试题:Majority Number III

给定一个整数数组和一个数k,多数元素是指出现次数超过数组大小1/k的数字。题目要求找到这个多数元素。算法思路是使用HashMap记录数组中元素的出现次数,当HashMap中有k个不同元素时进行抵消操作,最后HashMap中出现次数最多的元素即为答案。
摘要由CSDN通过智能技术生成

Given an array of integers and a number k, the majority number is the number that occursmore 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


思路:使用HashMap,存k个值,key为数组中的元素值,value为该值出现的次数。若同时有k个不同的元素在map中,则抵销一次,即所有value减一,并删除value为零的key,遍历一遍后,map中value最大的key为答案。

Solution:

public int majorityNumber3(int[] A, int k){
    	if (A == null || A.length == 0 || k > A.length) {
    		return -1;
    	}
    	
    	HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    	for (int i = 0; i < A.length; i++) {
    		if (map.containsKey(A[i])) {
    			map.put(A[i], map.get(A[i]) + 1);
    		} else if (map.size() < k) {
    			map.put(A[i], 1);
    		} else {
    			ArrayList<Integer> keys = new ArrayList<Integer>();
    			for (Integer key : map.keySet()){
    				keys.add(key);
    			}
    			for (Integer key : keys) {
    				map.put(key, map.get(key) - 1);
    				if (map.get(key) == 0) {
    					map.remove(key);
    				}
    			}
    		}
    	}
    	
    	int res = 0;
    	int num = 0;
    	for (Integer key : map.keySet()) {
    		if (num < map.get(key)) {
    			num = map.get(key);
    			res = key;
    		}
    	}
    	
    	return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值