当前位置:网站首页>The 20th day of the special assault version of the sword offer
The 20th day of the special assault version of the sword offer
2022-08-05 02:31:00 【hys__handsome】
小顶堆
- 第kBig is equivalent to,The penultimate after the sequence is ascendingk个数.
- 容易发现,倒数第kThe previous numbers are no longer available,Then we can throw away the useless ones,Then keep the sequence in order after insertion.
- 由于这里add会操作 1 0 4 10^4 104 次,So it needs less time complexity,It is easy to think of using a heap structure(大小保持为<= k k k ),或者multiset.
class KthLargest {
public:
int k = 0;
priority_queue<int,vector<int>,greater<int>> heap;
KthLargest(int k, vector<int>& nums) {
for(int num: nums) heap.push(num);
this->k = k;
}
int add(int val) {
heap.push(val);
while(heap.size() > k) heap.pop();
return heap.top();
}
};
剑指 Offer II 060. 出现频率最高的 k 个数字
方法一、Use the hash table to record the number of times,Then traverse the hash table to let the heap be maintained before k k k 大,时间复杂度就为 O ( N l o g k ) O(Nlogk) O(Nlogk) .
class Solution {
public:
typedef pair<int,int> PII;
unordered_map<int,int> cnts;
static bool cmp(const PII &a, const PII &b) {
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
for(int num: nums) {
cnts[num]++;
}
//自定义排序规则
priority_queue<PII,vector<PII>,decltype(&cmp)> heap(cmp);
for(auto p: cnts) {
if(heap.size() == k) {
//Keep the heap size no larger than k
if(heap.top().second < p.second) {
heap.pop();
heap.emplace(p);
}
} else heap.emplace(p);
}
vector<int> res;
while(heap.size()) {
res.emplace_back(heap.top().first);
heap.pop();
}
return res;
}
};
方法二、Use the hash table to record the number of times,Then sort out before taking outk大的数即可.时间 O ( N l o g N ) O(NlogN) O(NlogN)
class Solution {
public:
unordered_map<int,int> cnts;
static bool cmp(const pair<int,int> &a, const pair<int,int> &b) {
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
int maxx = 0;
for(int num: nums) {
cnts[num]++;
}
vector<pair<int,int>> ls;
for(auto p: cnts) {
ls.emplace_back(p);
}
sort(ls.begin(),ls.end(),cmp);
ls.erase(ls.begin()+k,ls.end());
vector<int> res;
for(auto num: ls) res.emplace_back(num.first);
return res;
}
};
- It's easy to think of a way:Violent all pairs,然后排序取前 k k k 小,时间复杂度是 O ( N 2 ) O(N^2) O(N2) It will time out here.
- 仔细思考会发现, n u m s 1 [ 0 ] + n u m s 2 [ 0 ] nums1[0]+nums2[0] nums1[0]+nums2[0] 一定是最小的,And then the next smallest must be one of them: n u m s 1 [ 0 ] + n u m s 2 [ 1 ] nums1[0]+nums2[1] nums1[0]+nums2[1] 、 n u m s 1 [ 1 ] + n u m s 2 [ 0 ] nums1[1]+nums2[0] nums1[1]+nums2[0] ,以此类推,This way we don't have to traverse all pairs, just use the rules to find the first few,Here, a small top heap is needed to maintain the relationship between pairs.
class Solution {
public:
typedef pair<int,int> PII;
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
auto cmp = [&nums1,&nums2](const PII &a, const PII &b) {
return nums1[a.first]+nums2[a.second] > nums1[b.first]+nums2[b.second];
};
int n = nums1.size();
int m = nums2.size();
priority_queue<PII,vector<PII>,decltype(cmp)> heap(cmp);
for(int i = 0; i < min(k,n); i++) {
heap.emplace(i,0);
}
vector<vector<int>> res;
while(k-- && heap.size()) {
auto [x,y] = heap.top();
heap.pop();
res.push_back({
nums1[x],nums2[y]});
if(y+1 < m) heap.emplace(x,y+1);
}
return res;
}
};
参考:https://leetcode.cn/problems/qn8gGX/solution/he-zui-xiao-de-k-ge-shu-dui-by-leetcode-eoce6/
边栏推荐
- 高数_复习_第1章:函数、极限、连续
- CPDA|运营人如何从负基础学会数据分析(SQL)
- Error: Not a signal or slot declaration
- 网络安全与元宇宙:找出薄弱环节
- nodeJs--封装路由
- Jincang database KingbaseES V8 GIS data migration solution (3. Data migration based on ArcGIS platform to KES)
- 蚁剑高级模块开发
- 线上MySQL的自增id用尽怎么办?
- SuperMap iDesktop.Net之布尔运算求交——修复含拓扑错误复杂模型
- 【日常训练】1403. 非递增顺序的最小子序列
猜你喜欢
迁移学习——Joint Geometrical and Statistical Alignment for Visual Domain Adaptation
Understand the recommendation system in one article: Recall 06: Two-tower model - model structure, training method, the recall model is a late fusion feature, and the sorting model is an early fusion
Simple implementation of YOLOv7 pre-training model deployment based on OpenVINO toolkit
DAY23: Command Execution & Code Execution Vulnerability
RAID磁盘阵列
【C语言】详解栈和队列(定义、销毁、数据的操作)
js中try...catch和finally的用法
[Decryption] Can the NFTs created by OpenSea for free appear in my wallet without being chained?
Using OpenVINO to implement the flying paddle version of the PGNet inference program
C语言实现简单猜数字游戏
随机推荐
亚马逊云科技携手中科创达为行业客户构建AIoT平台
KingbaseES V8 GIS data migration solution (2. Introduction to the capabilities of Kingbase GIS)
SDC简介
剑指offer专项突击版第20天
How to deal with your own shame
.Net C# 控制台 使用 Win32 API 创建一个窗口
蚁剑高级模块开发
【解密】OpenSea免费创造的NFT都没上链竟能出现在我的钱包里?
C语言实现简单猜数字游戏
Greenplum数据库故障分析——版本升级后gpstart -a为何返回失败
Unleashing the engine of technological innovation, Intel joins hands with ecological partners to promote the vigorous development of smart retail
行业案例|世界 500 强险企如何建设指标驱动的经营分析系统
直播预告|30分钟快速入门!来看可信分布式AI链桨的架构设计
Amazon Cloud Technology joins hands with Thundersoft to build an AIoT platform for industry customers
转:查尔斯·汉迪:你是谁,比你做什么更重要
DAY22:sqli-labs 靶场通关wp(Less01~~Less20)
Access Characteristics of Constructor under Inheritance Relationship
01 【前言 基础使用 核心概念】
协作D2D局部模型聚合的半分散联合学习
后期学习计划