347:前 K 个高频元素

This commit is contained in:
huangge1199 2021-09-03 13:43:47 +08:00
parent d01fd23854
commit 555dfe5590
2 changed files with 108 additions and 0 deletions

View File

@ -0,0 +1,77 @@
//给你一个整数数组 nums 和一个整数 k 请你返回其中出现频率前 k 高的元素你可以按 任意顺序 返回答案
//
//
//
// 示例 1:
//
//
//输入: nums = [1,1,1,2,2,3], k = 2
//输出: [1,2]
//
//
// 示例 2:
//
//
//输入: nums = [1], k = 1
//输出: [1]
//
//
//
// 提示
//
//
// 1 <= nums.length <= 10
// k 的取值范围是 [1, 数组中不相同的元素的个数]
// 题目数据保证答案唯一换句话说数组中前 k 个高频元素的集合是唯一的
//
//
//
//
// 进阶你所设计算法的时间复杂度 必须 优于 O(n log n) 其中 n 是数组大小
// Related Topics 数组 哈希表 分治 桶排序 计数 快速选择 排序 优先队列 👍 853 👎 0
package leetcode.editor.cn;
import java.util.*;
//347: K 个高频元素
class TopKFrequentElements {
public static void main(String[] args) {
//测试代码
Solution solution = new TopKFrequentElements().new Solution();
solution.topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2);
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
counts.put(num, counts.getOrDefault(num, 0) + 1);
}
Map<Integer, List<Integer>> map = new HashMap<>();
for (int key : counts.keySet()) {
List<Integer> temp = map.getOrDefault(counts.get(key), new ArrayList<>());
temp.add(key);
map.put(counts.get(key), new ArrayList<>(temp));
}
List<Integer> list = new ArrayList<>(map.keySet());
int[] arr = new int[k];
int index = 0;
for (int i = list.size() - 1; i >= 0; i--) {
List<Integer> temp = map.get(list.get(i));
for (int j = index; j < index + temp.size(); j++) {
arr[j] = temp.get(j - index);
}
index += temp.size();
if (index == k) {
break;
}
}
return arr;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,31 @@
<p>给你一个整数数组 <code>nums</code> 和一个整数 <code>k</code> ,请你返回其中出现频率前 <code>k</code> 高的元素。你可以按 <strong>任意顺序</strong> 返回答案。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入: </strong>nums = [1,1,1,2,2,3], k = 2
<strong>输出: </strong>[1,2]
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入: </strong>nums = [1], k = 1
<strong>输出: </strong>[1]</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>k</code> 的取值范围是 <code>[1, 数组中不相同的元素的个数]</code></li>
<li>题目数据保证答案唯一,换句话说,数组中前 <code>k</code> 个高频元素的集合是唯一的</li>
</ul>
<p> </p>
<p><strong>进阶:</strong>你所设计算法的时间复杂度 <strong>必须</strong> 优于 <code>O(n log n)</code> ,其中 <code>n</code><em> </em>是数组大小。</p>
<div><div>Related Topics</div><div><li>数组</li><li>哈希表</li><li>分治</li><li>桶排序</li><li>计数</li><li>快速选择</li><li>排序</li><li>堆(优先队列)</li></div></div><br><div><li>👍 853</li><li>👎 0</li></div>