比如,一个数组为:[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)。
下面采用第三种方式:
-
- 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);
- }
-
- List<Integer>[] keyList = new List[numbers.length];
- for(int key:map.keySet()){
-
- int a = map.get(key);
-
- 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;
- }