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

边栏推荐
- What did you learn about cheating after you went to college?
- 架构师毕业总结
- How to create a pyramid with openmesh
- STC 32-bit 8051 single chip microcomputer development example tutorial three program compilation setting and download
- 宅男壁纸大全微信小程序源码-带动态壁纸支持多种流量主
- C # joint halcon Application - Dahua Camera Collection class
- C # joint Halcon application - Dahua camera acquisition class
- fastDFS入门
- internship:逐渐迈向项目开发
- 牛客编程题--必刷101之字符串(高效刷题,举一反三)
猜你喜欢

关联线探究,如何连接流程图的两个节点

Win11 how to hide the taskbar? Win11 method to hide the taskbar

Vulnerability recurrence - Net ueeditor upload

独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作

On the next generation entrance of the metauniverse -- the implementation of brain computer interface

RichView RichEdit SRichViewEdit PageSize 页面设置与同步

Arduino Stepper库驱动28BYJ-48步进电机测试程序

优质笔记软件综合评测和详细盘点(一) Notion、Obsidian、RemNote、FlowUs

STC 32-bit 8051 single chip microcomputer development example tutorial three program compilation setting and download

如何用OpenMesh创建一个四棱锥
随机推荐
Write blog documents
EDA工具对芯片产业的重要性知识科普
RichView TRVDocParameters 页面参数设置
目標檢測——Yolo系列
Vulnerability recurrence - Net ueeditor upload
Penetration tools - trustedsec's penetration testing framework (PTF)
利用QEventLoop实现同步等待槽函数返回
On the usage of a magic function
#yyds干货盘点#SQL聚合查询方法总结
Internship: complex JSON format data compilation interface
math_ Use differentiation to calculate approximate value
Problems encountered in installing MySQL in docker Ubuntu container
架构师毕业总结
Error in installing sharp
Detailed explanation and code example of affinity propagation clustering calculation formula based on graph
数据分析师听起来很高大上?了解这几点你再决定是否转型
Face recognition system opencv face detection
2022年低压电工考试试题及答案
喜马拉雅自研网关架构演进过程
Interesting! Database is also serverless!