当前位置:网站首页>leetcode刷题:栈与队列06(前 K 个高频元素)
leetcode刷题:栈与队列06(前 K 个高频元素)
2022-07-01 19:16:00 【涛涛英语学不进去】
347.前 K 个高频元素
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
- 输入: nums = [1,1,1,2,2,3], k = 2
- 输出: [1,2]
示例 2:
- 输入: nums = [1], k = 1
- 输出: [1]
提示:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O ( n log n ) O(n \log n) O(nlogn) , n 是数组的大小。
- 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
- 你可以按任意顺序返回答案。
又是一个中等题一发入魂,飘了hhhhh
思路:
哈希表计算每个数字出现的次数
键、值分别放到两个数组,按值排序,键镜像同步变换位置
返回前K个数字。
package com.programmercarl.stacks_queues;
import java.util.HashMap;
/** * @ClassName TopKFrequent * @Descriotion TODO * @Author nitaotao * @Date 2022/6/30 14:13 * @Version 1.0 * https://leetcode.cn/problems/top-k-frequent-elements/ * 347. 前 K 个高频元素 **/
public class TopKFrequent {
public static int[] topKFrequent(int[] nums, int k) {
/** * 思路: * 哈希表计数 */
HashMap<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.put(nums[i], 1);
}
}
int[] keys = new int[map.size()];
int[] values = new int[map.size()];
int index = 0;
for (Integer key : map.keySet()) {
keys[index] = key;
values[index] = map.get(key);
index++;
}
//value 排序,key 镜像同步交换
for (int i = 0; i < values.length-1; i++) {
for (int j = i+1; j < values.length; j++) {
if (values[i] < values[j]) {
int tempValue = values[i];
values[i] = values[j];
values[j] = tempValue;
int tempKey = keys[i];
keys[i] = keys[j];
keys[j] = tempKey;
}
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = keys[i];
}
return result;
}
}

看题解还有另一个思路,是我们之前上课时老师讲的思路,大顶堆思想。
public static int[] topKFrequent(int[] nums, int k) {
/** * 思路: * 哈希表计数 */
HashMap<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.put(nums[i], 1);
}
}
//大顶堆思想
//优先级队列,按值大小排序
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
for(Map.Entry<Integer,Integer>entry : map.entrySet()) {
queue.offer(entry);
//只保留前k个数
if (queue.size() > k) {
queue.poll();
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = queue.poll().getKey();
}
return result;
}

边栏推荐
- 300题线性代数 第四讲 线性方程组
- 3D panoramic model display visualization technology demonstration
- Oracle deadlock test
- Redis installation and startup in Windows environment (background startup)
- Niuke programming question -- must brush the string of 101 (brush the question efficiently, draw inferences from one instance)
- RichView RichEdit SRichViewEdit PageSize 页面设置与同步
- Develop those things: easycvr cluster device management page function display optimization
- Target detection - Yolo series
- 基于图的 Affinity Propagation 聚类计算公式详解和代码示例
- PLC模拟量输入 模拟量转换FB S_ITR(三菱FX3U)
猜你喜欢

tensorflow 张量做卷积,输入量与卷积核维度的理解

《软件工程导论(第六版)》 张海藩 复习笔记

Détection des cibles - série Yolo

After adding cocoapods successfully, the header file cannot be imported or an error is reported in not found file

2022年高处安装、维护、拆除考题模拟考试平台操作

PLC模拟量输入 模拟量转换FB S_ITR(三菱FX3U)

Simple but modern server dashboard dashdot

Practical project notes (I) -- creation of virtual machine

【Leetcode】最大连续1的个数

Items in richview documents
随机推荐
PHP gets the external chain address of wechat applet and applet store
C # joint halcon Application - Dahua Camera Collection class
数据分析师听起来很高大上?了解这几点你再决定是否转型
2022安全员-A证考题及在线模拟考试
如果浏览器被意外关闭,react怎么缓存用户填写的表单?
Stack overflow 2022 developer survey: where is the industry going?
switch 有四样写法你知道么
Learn white box test case design from simple to deep
【C语言】详解 memset() 函数用法
2022/6/8-2022/6/12
编译原理复习笔记
Penetration tools - trustedsec's penetration testing framework (PTF)
Realize pyramids through JS (asterisk pyramid, palindrome symmetric digital pyramid)
Target detection - Yolo series
写博客文档
How to create a pyramid with openmesh
运动捕捉系统原理
Detailed explanation and code example of affinity propagation clustering calculation formula based on graph
[multithreading] realize the singleton mode (hungry and lazy) realize the thread safe singleton mode (double validation lock)
[mysql] install mysql5.7