Java如何找出数组中前k个高频元素

比如,一个数组为:[1,2,3,5,2,3,5,7,7,7,5,7 ]前2个高频元素就是7和5。

思路:最简单的办法就是采用两层for循环去遍历,时间复杂度为O(n2)。

方法二:先用快速排序将数组排序,然后依次找出前k个高频元素,时间复杂度O(NLogN)。

方法三:可以采用HashMap,这种方式时间复杂度为O(N),空间复杂度O(N)。

下面采用第三种方式:

public class test {
	//定义统计数组里每个数字出现的次数HashMap;
	static HashMap<Integer, Integer> map;
	public static void main(String[] args) {
		int[] num = {1,2,3,5,2,3,5,7,7,7,5,7};
		ArrayList<Integer> nums = topK(num,4);
		System.out.println(nums);
	}
    public static  ArrayList<Integer> topK(int[] numbers , int k){
    	map = new HashMap<Integer,Integer>();
    	for(int i = 0; i<numbers.length; i++){
    		Integer count = map.get(numbers[i]);
    		if(count ==null){
    			count=0;
    		}
    		map.put(numbers[i], count+1);
    	}
    	//构造一个数组来放map中的key;
    	List<Integer>[] keyList = new List[numbers.length];
    	 for(int key:map.keySet()){  
    		 //map中数出现的次数;
    	        int a = map.get(key);
    	        //将map中的key放在arrayList的里
    	        if(keyList[a]==null){
    	            ArrayList<Integer> temp = new ArrayList<Integer>();  
    	            temp.add(key);  
    	            keyList[a] = temp;  
    	        }else{  
    	        	keyList[a].add(key);  
    	        }  
    	    }  
        ArrayList<Integer> res = new ArrayList<Integer>();  
        for(int i=keyList.length-1;i>=0&&res.size()<k;i--){  
            if(keyList[i]!=null){  
                res.addAll(keyList[i]);  
            }  
        }
	         return res;  
   }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值