版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangwei282367751/article/details/52504361
比如,一个数组为:[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;
}
}