LeetCode 1338. 数组大小减半

题目链接

1338. 数组大小减半

题目分析

这个题没啥好说的,只能直接先统计每个数字出现的次数,然后优先删除出现次数多的,因为题目要求我们得到的结果集是“最小”的,所以就利用贪心的思想了。
我写这个题主要是为了记录优先队列的使用,因为刷题那么久了,真正用过优先队列的次数却不是很多。

代码实现

class Solution {
    public int minSetSize(int[] arr) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int num : arr){
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        int res = 0;
        int count = 0;
        PriorityQueue<Integer> heap = new PriorityQueue<>((n1, n2) -> n2 - n1);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            heap.offer(entry.getValue());
        }
        while(!heap.isEmpty()){
            count += heap.poll();
            res++;
            if(count >= (arr.length >> 1)){
                break;
            }
        }
        return res;
    }
}

总结

还是得多实操一下各种数据结构,不然这个题排起序来真的各种TLE

原文地址:https://www.cnblogs.com/ZJPaang/p/13409275.html