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

来源:互联网 发布:js 获取class值 编辑:程序博客网 时间:2024/05/16 23:50

比如,一个数组为:[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)。

下面采用第三种方式:

[java] view plain copy
  1. public class test {  
[java] view plain copy
  1. //定义统计数组里每个数字出现的次数HashMap;  
  2. static HashMap<Integer, Integer> map;  
  3. public static void main(String[] args) {  
  4.     int[] num = {1,2,3,5,2,3,5,7,7,7,5,7};  
  5.     ArrayList<Integer> nums = topK(num,4);  
  6.     System.out.println(nums);  
  7. }  
[java] view plain copy
  1.  public static  ArrayList<Integer> topK(int[] numbers , int k){  
  2.     map = new HashMap<Integer,Integer>();  
  3.     for(int i = 0; i<numbers.length; i++){  
  4.         Integer count = map.get(numbers[i]);  
  5.         if(count ==null){  
  6.             count=0;  
  7.         }  
  8.         map.put(numbers[i], count+1);  
  9.     }  
  10.     //构造一个数组来放map中的key;  
  11.     List<Integer>[] keyList = new List[numbers.length];  
  12.      for(int key:map.keySet()){    
  13.          //map中数出现的次数;  
  14.             int a = map.get(key);  
  15.             //将map中的key放在arrayList的里  
  16.             if(keyList[a]==null){  
  17.                 ArrayList<Integer> temp = new ArrayList<Integer>();    
  18.                 temp.add(key);    
  19.                 keyList[a] = temp;    
  20.             }else{    
  21.                 keyList[a].add(key);    
  22.             }    
  23.         }    
  24.      ArrayList<Integer> res = new ArrayList<Integer>();    
  25.      for(int i=keyList.length-1;i>=0&&res.size()<k;i--){    
  26.          if(keyList[i]!=null){    
  27.              res.addAll(keyList[i]);    
  28.          }    
  29.      }  
  30.        return res;    
  31. }  
0 0
原创粉丝点击