leetcode 1338. Reduce Array Size to The Half | 1338. 数组大小减半(Java)
2021/7/7 14:06:30
本文主要是介绍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)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现