leetcode-前K个高频元素

给定一个非空的整数数组,返回其中出现频率前 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]

说明:

  • 你可以假设给定的 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , 是数组的大小。

思路:利用数据结构,map来添加。因此map中记录了nums[i]为key, 出现的次数count为values。

之后通过Arrays.sort(map)来进行排序。

 Map.entrySet() 这个方法返回的是一个Set<Map.Entry<K,V>>,Map.Entry 是Map中的一个接口,他的用途是表示一个映射项(里面有Key和Value),而Set<Map.Entry<K,V>>表示一个映射项的Set。Map.Entry里有相应的getKey和getValue方法。

class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
    List<Integer> res=new ArrayList();
       Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<nums.length;i++){
            if(!map.containsKey(nums[i])){
                map.put(nums[i],1);
            }else{
                map.put(nums[i],map.get(nums[i])+1);
            }
        }
       List<Map.Entry<Integer,Integer>> list=new ArrayList(map.entrySet());
        //然后通过比较器来实现排序
       Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){
          public int compare(Map.Entry<Integer,Integer> a,Map.Entry<Integer,Integer> b){
               return b.getValue().compareTo(a.getValue());     //倒序排列
           }
       });
    for(Map.Entry<Integer,Integer> mapping:list){
            res.add(mapping.getKey());
            if(res.size()==k){
                break;
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/patatoforsyj/p/9544649.html