Leetcode 刷题笔记----347.前k个高频元素(排序)

题目描述:

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

示例 1:

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

示例 2:

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

思路:

首先,使用hashmap记录每个数字出现的字数;然后将hashmap按照value值从大到小排序,最后取前k个元素的key值即可。

代码:

class Solution {
    public List topKFrequent(int[] nums, int k) {
        HashMap map=new HashMap<>();
        for (int n: nums) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        List res=new ArrayList<>();
        ArrayList> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                //按照value值降序,前边去掉负号变为升序
                return -o1.getValue().compareTo(o2.getValue());   
                //return -o1.getKey().compareTo(o2.getKey());   按照key值降序
            }
        });

        Iterator> iterator = list.iterator();
        for(Map.Entry m : list){
            if(res.size()==k) break;
            res.add(m.getKey());
        }
        return res;
    }
}

 

你可能感兴趣的:(LeetCode-排序)