https://leetcode.com/problems/reduce-array-size-to-the-half/
先统计每个数字出现次数,然后给出现次数排序。出现次数多者,先被选中。
比较简单,官方题解也是 O(nlogn) 的时间复杂度。不知道为啥是个 medium 题。
class Solution { public int minSetSize(int[] arr) { Map<Integer, Integer> map = new HashMap<>(); for (Integer n : arr) { if (map.containsKey(n)) map.put(n, map.get(n) + 1); else map.put(n, 1); } int[] count = new int[map.size()]; int i = 0; for (Integer c : map.values()) count[i++] = c; Arrays.sort(count); int sum = 0; i = count.length; while (sum < arr.length / 2) { sum += count[--i]; } return count.length - i; } }