当前位置:网站首页>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;
}

边栏推荐
- deb文件安装
- 8K HDR!|为 Chromium 实现 HEVC 硬解 - 原理/实测指南
- 《軟件工程導論(第六版)》 張海藩 複習筆記
- 独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
- C # joint Halcon application - Dahua camera acquisition class
- 2022安全员-A证考题及在线模拟考试
- C#聯合halcon應用——大華相機采集類
- STC 32-bit 8051 single chip microcomputer development example tutorial II i/o working mode and its configuration
- [Mysql]安装Mysql5.7
- 2022安全员-B证考试练习题模拟考试平台操作
猜你喜欢

Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers

Hls4ml reports an error the board_ part definition was not found for tul. com. tw:pynq-z2:part0:1.0.

Realize pyramids through JS (asterisk pyramid, palindrome symmetric digital pyramid)

Develop those things: easycvr platform adds playback address authentication function

EURA欧瑞E1000系列变频器使用PID实现恒压供水功能的相关参数设置及接线

STC 32-bit 8051 single chip microcomputer development example tutorial II i/o working mode and its configuration

《軟件工程導論(第六版)》 張海藩 複習筆記
![[mysql] install mysql5.7](/img/c4/d7fb5ddf8e7be31f7a9ad68409e584.png)
[mysql] install mysql5.7

小鸟逃票登机,如何反思,应如何解决,飞机为何怕小鸟?

Common components of flask
随机推荐
NSI脚本的测试
天气预报小程序源码 天气类微信小程序源码
Win11怎么关闭开机自启动软件
Richview trvdocparameters page parameter settings
Develop those things: easycvr cluster device management page function display optimization
Keras机器翻译实战
牛客编程题--必刷101之字符串(高效刷题,举一反三)
Problems encountered in installing MySQL in docker Ubuntu container
Powerful, easy-to-use, professional editor / notebook software suitable for programmers / software developers, comprehensive evaluation and comprehensive recommendation
How to connect the two nodes of the flow chart
在技术升级中迎合消费者需求,安吉尔净水器“价值战”的竞争之道
Review notes of Zhang Haifan in introduction to software engineering (Sixth Edition)
What did you learn about cheating after you went to college?
Solve the problem of slow or failed vscode download
Test of NSI script
Internship: complex JSON format data compilation interface
How to create a pyramid with openmesh
math_利用微分算近似值
math_ Use differentiation to calculate approximate value
Comprehensive evaluation and detailed inventory of high-quality note taking software (I) note, obsedian, remnote, flowus