leetcode 1338. Reduce Array Size to The Half | 1338. 数组大小减半(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 1338. Reduce Array Size to The Half | 1338. 数组大小减半(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
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;} }總結
以上是生活随笔為你收集整理的leetcode 1338. Reduce Array Size to The Half | 1338. 数组大小减半(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 54. Spiral
- 下一篇: leetcode 309. Best T