当前位置: 首页 > news >正文

【leetcode】优先队列题目总结

 优先队列的底层是最大堆或最小堆

priority_queue<Type, Container, Functional>;

  • Type是要存放的数据类型
  • Container是实现底层堆的容器,必须是数组实现的容器,如vector、deque
  • Functional是比较方式/比较函数/优先级

priority_queue<Type>;

此时默认的容器是vector,默认的比较方式是大顶堆less<type>

常见的函数有:

  • top()
  • pop()
  • push()
  • emplace()
  • empty()
  • size()

 基本类型:

//小顶堆
priority_queue <int,vector<int>,greater<int> > q;
//大顶堆
priority_queue <int,vector<int>,less<int> >q;
//默认大顶堆
priority_queue<int> a;//pair
priority_queue<pair<int, int> > a;
pair<int, int> b(1, 2);
pair<int, int> c(1, 3);
pair<int, int> d(2, 5);
a.push(d);
a.push(c);
a.push(b);
while (!a.empty()) 
{cout << a.top().first << ' ' << a.top().second << '\n';a.pop();
}
//输出结果为:
2 5
1 3
1 2

 自定义类型:

struct fruit
{string name;int price;
};// 1. 重载运算符  重载”<”
// 大顶堆
struct fruit
{string name;int price;friend bool operator < (fruit f1, fruit f2){return f1.peice < f2.price;}
};// 小顶堆
struct fruit
{string name;int price;friend bool operator < (fruit f1, fruit f2){return f1.peice > f2.price;  //此处是 >}
};// 此时优先队列的定义应该如下
priority_queue<fruit> q;// 2. 仿函数
// 大顶堆
struct myComparison
{bool operator () (fruit f1, fruit f2){return f1.price < f2.price;}
};struct myComparison
{bool operator () (fruit f1, fruit f2){return f1.price > f2.price;  //此处是 >}
};// 此时优先队列的定义应该如下
priority_queue<fruit, vector<fruit>, myComparison> q;

--------------------------------------------------------------------------------------------------------



215. 数组中的第K个最大元素

class Solution {
public:int findKthLargest(vector<int>& nums, int k) {priority_queue<int, vector<int>, greater<int>> pq;for (auto num : nums) {pq.push(num);if (pq.size() > k) {pq.pop();}}return pq.top();}
};

快排思想解法:

class Solution {
public:int partition(vector<int>& nums, int left, int right) {int randIndex = left + rand() % (right - left + 1);swap(nums[left], nums[randIndex]);int pivot = nums[left];while (left < right) {while (left < right && nums[right] >= pivot) {right--;}nums[left] = nums[right];while (left < right && nums[left] <= pivot) {left++;}nums[right] = nums[left];}nums[left] = pivot;return left;}int findKthLargest(vector<int>& nums, int k) {int left = 0, right = nums.size() - 1;int targetIndex = nums.size() - k;while (left <= right) {int mid = partition(nums, left, right);if (mid == targetIndex) {return nums[mid];} else if (mid < targetIndex) {left = mid + 1;} else {right = mid - 1;}}return INT_MIN;}
};

347. 前 K 个高频元素

class Solution {
public:struct compare {bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {return lhs.second > rhs.second;}};vector<int> topKFrequent(vector<int>& nums, int k) {unordered_map<int, int> mp;for (auto& num : nums) {mp[num]++;}priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq;for (auto& item : mp) {pq.push(item);if (pq.size() > k) {pq.pop();}}vector<int> res;while (!pq.empty()) {res.push_back(pq.top().first);pq.pop();}return res;}
};

703. 数据流中的第 K 大元素

class KthLargest {
private:priority_queue<int, vector<int>, greater<int>> _pq;int _k;
public:KthLargest(int k, vector<int>& nums) {_k = k;for (auto& num : nums) {add(num);}}int add(int val) {_pq.push(val);if (_pq.size() > _k) {_pq.pop();}return _pq.top();}
};/*** Your KthLargest object will be instantiated and called as such:* KthLargest* obj = new KthLargest(k, nums);* int param_1 = obj->add(val);*/

295. 数据流的中位数

  • 大顶堆维护左半部分数据
  • 小顶堆维护右半部分数据
class MedianFinder {
public:priority_queue<int, vector<int>, less<int>> leftHeap;priority_queue<int, vector<int>, greater<int>> rightHeap;MedianFinder() {}void addNum(int num) {if (leftHeap.size() == rightHeap.size()) {rightHeap.push(num);leftHeap.push(rightHeap.top());rightHeap.pop();} else {leftHeap.push(num);rightHeap.push(leftHeap.top());leftHeap.pop();}}double findMedian() {return leftHeap.size() == rightHeap.size() ? (leftHeap.top() + rightHeap.top()) * 0.5 : leftHeap.top();}
};/*** Your MedianFinder object will be instantiated and called as such:* MedianFinder* obj = new MedianFinder();* obj->addNum(num);* double param_2 = obj->findMedian();*/

23. 合并 K 个升序链表

优先队列

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:struct compare {bool operator() (const ListNode* lhs, const ListNode* rhs) {return lhs->val > rhs->val;}};ListNode* mergeKLists(vector<ListNode*>& lists) {priority_queue<ListNode*, vector<ListNode*>, compare> pq;for (auto& node : lists) {if (node != nullptr) {pq.push(node);}}ListNode* dummy = new ListNode(-1);ListNode* cur = dummy;while (!pq.empty()) {ListNode* node = pq.top();pq.pop();cur->next = node;cur = cur->next;if (node->next != nullptr) {pq.push(node->next);}}return dummy->next;}
};

二分+递归

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {if (list1 == nullptr) {return list2;}if (list2 == nullptr) {return list1;}if (list1->val < list2->val) {list1->next = mergeTwoLists(list1->next, list2);return list1;} else {list2->next = mergeTwoLists(list1, list2->next);return list2;}return nullptr;}ListNode* mergeLists(vector<ListNode*>& lists, int left, int right) {if (left > right) {return nullptr;}if (left == right) {return lists[left];}int mid =  left + (right - left) / 2;return mergeTwoLists(mergeLists(lists, left, mid), mergeLists(lists, mid + 1, right));}ListNode* mergeKLists(vector<ListNode*>& lists) {return mergeLists(lists, 0, lists.size() - 1);}
};

相关文章:

【leetcode】优先队列题目总结

优先队列的底层是最大堆或最小堆 priority_queue<Type, Container, Functional>; Type是要存放的数据类型Container是实现底层堆的容器&#xff0c;必须是数组实现的容器&#xff0c;如vector、dequeFunctional是比较方式/比较函数/优先级 priority_queue<Type>…...

typescript 中的泛型

泛型&#xff1a;解决 类、接口、方法的复用性、以及对不特定数据类型的支持 传入的参数与返回参数类型一致 泛型函数 // T表示泛型&#xff0c;具体什么类型是调用这个方法的时候决定的 function getData<T>(value: T): T {return value } getData<number>(123) …...

计算方法实验2(补充):列主元消元法解线性方程组

C源代码 #include<bits/stdc.h> using namespace std;// 列主元消去法求解线性方程组 vector<long double> Column_Elimination(vector<vector<long double>> A, vector<long double> b);int main() {vector<vector<long double>> …...

Qt扫盲-Qt D-Bus概述

Qt D-Bus概述 一、概述二、总线三、相关概念1. 消息2. 服务名称3. 对象的路径4. 接口5. 备忘单 四、调试五、使用Qt D-Bus 适配器1. 在 D-Bus 适配器中声明槽函数1. 异步槽2. 只输入槽3. 输入输出槽4. 自动回复5. 延迟回复 一、概述 D-Bus是一种进程间通信(IPC)和远程过程调用…...

懒洋洋作业讲解

懒洋洋作业讲解 环境配置 1.软件下载&#xff1a;DCloud - HBuilder、HBuilderX、uni-app、uniapp、5、5plus、mui、wap2app、流应用、HTML5、小程序开发、跨平台App、多端框架 2.软件介绍 HBuilder是由DCloud&#xff08;数字天堂&#xff09;推出的一款面向HTML5的Web开发…...

vue3 + ts实现canvas绘制的waterfall

实际运行效果&#xff08;仅包含waterfall图表部分&#xff09; component.vue <template><div ref"heatmap" :style"{ height: props.containerHeight px }" /> </template><script setup> import ColorMap from "color…...

代码随想录算法训练营第四十四天

sad的一天&#xff0c;明天开始上班&#xff0c;而且娃还行&#xff0c;媳妇儿状态不稳定&#xff0c;太难了也&#xff01;&#xff01;&#xff01; 完全背包 #include<vector> #include<iostream> using namespace::std; int main(){int N;//种类int V;//空间ci…...

【3dmax笔记】027:配置修改器集、工具栏自定义与加载

文章目录 一、配置修改器集二、自定义工具栏三、加载工具栏 一、配置修改器集 可以把自己常用的修改命令放到右边框中的部分&#xff0c;便于自己的操作&#xff0c;省去了每次都要花半天时间找命令的尴尬。新建一个二维或者三维物体&#xff0c;点击修改面板&#xff0c;点击…...

Reactor模型详解

目录 1.概述 2.Single Reactor 3.muduo库的Multiple Reactors模型如下 1.概述 维基百科对Reactor模型的解释 The reactor design pattern is an event handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs.…...

内存卡罢工,数据危机?别急,有救!

在日常生活和工作中&#xff0c;我们越来越依赖于各种电子设备来存储重要数据。其中&#xff0c;内存卡因其便携性和大容量而广受欢迎。然而&#xff0c;当内存卡突然损坏打不开时&#xff0c;我们该如何应对&#xff1f;本文将为您详细解析这一问题&#xff0c;并提供有效的解…...

python爬虫实战

import requests import json yesinput(输入页数&#xff1a;) yesint(yes)headers {"accept": "application/json, text/plain, */*","accept-language": "zh-CN,zh;q0.9","content-type": "application/json",…...

k8s 资源文件参数介绍

Kubernetes资源文件yaml参数介绍 yaml 介绍 yaml 是一个类似 XML、JSON 的标记性语言。它强调以数据为中心&#xff0c;并不是以标识语言为重点例如 SpringBoot 的配置文件 application.yml 也是一个 yaml 格式的文件 语法格式 通过缩进表示层级关系不能使用tab进行缩进&am…...

mac系统安装steam报错-解决办法

今天给虚拟机装了个苹果系统&#xff0c;然后想装个steam&#xff0c;从steam的官方下载安装steam_osx.dmg时&#xff0c;总是报“steam_osx已损坏&#xff0c;无法打开&#xff0c;请移动到废纸篓“。搜了一下找到了解决办法&#xff0c;这里记录一下。 双击steam_osx.dmg时&…...

这个簇状柱形图怎么添加百分比?

这个图表是excel默认的图表配色&#xff0c;有的人做出来都那个百分比&#xff0c;一起来做一个这样的图表。 1.插入图表 选中数据区域&#xff0c;点击 插入选项卡&#xff0c;在图表那一栏&#xff0c;点一下柱形图右侧那个倒三角&#xff0c;在弹邮对话框中&#xff0c;选…...

Tomact安装配置及使用(超详细)

文章目录 web相关知识概述web简介(了解)软件架构模式(掌握)BS&#xff1a;browser server 浏览器服务器CS&#xff1a;client server 客户端服务器 B/S和C/S通信模式特点(重要)web资源(理解)资源分类 URL请求路径(理解)作用介绍格式浏览器通过url访问服务器的过程 服务器(掌握)…...

web后端——netbeans ide +jsp+servlet开发学习总结

目录 jsp基础 netbeans开发工具问题HTTP Status 405 - HTTP method POST is not supported......netbeans 提示无法启动GlassFish Server 4.1.1:服务器未运行时, HTTP 或 HTTPS 监听程序端口已被占用404 问题netbeans中项目中有多个html文件,如何单独运行某个文件&#xff1f;n…...

使用request-try-notifyState流程实现UI控制与状态反馈的完整闭环

1. 前言 在Qt编程时&#xff0c;我们经常会在界面上添加一些按钮&#xff0c;当按钮被点击时&#xff0c;执行某段代码&#xff0c;例如显示一个对话框、关闭窗口&#xff0c;保存文件等等。 这种由UI控件触发某种信号&#xff0c;通过信号槽触发目的代码执行的场景非常多。这…...

屏蔽罩材质和厚度对屏蔽效能的影响

​ 一&#xff0e;屏蔽效能的影响因素 屏蔽效能的影响因素主要有两个方面&#xff1a;屏蔽材料的特性和厚度&#xff1b;如下图所示&#xff0c;电磁波经过不同媒介时&#xff0c;会在分界面形成反射&#xff0c;穿过界面的电磁波一部分被反射回去&#xff0c;这部分能量损失…...

Qt简单离线音乐播放器

有上传本地音乐文件&#xff0c;播放&#xff0c;暂停&#xff0c;拖拉进度条等功能的播放器。 mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QMediaPlayer> #include <QFileDialog> #include <QTime&g…...

微信小程序常用的api

基础API&#xff1a; wx.request&#xff1a;用于发起网络请求&#xff0c;支持GET、POST等方式&#xff0c;是获取网络数据的主要手段。wx.showToast&#xff1a;显示消息提示框&#xff0c;通常用于向用户展示操作成功、失败或加载中等状态。wx.showModal&#xff1a;显示模态…...

K8S认证|CKS题库+答案| 11. AppArmor

目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作&#xff1a; 1&#xff09;、切换集群 2&#xff09;、切换节点 3&#xff09;、切换到 apparmor 的目录 4&#xff09;、执行 apparmor 策略模块 5&#xff09;、修改 pod 文件 6&#xff09;、…...

Axios请求超时重发机制

Axios 超时重新请求实现方案 在 Axios 中实现超时重新请求可以通过以下几种方式&#xff1a; 1. 使用拦截器实现自动重试 import axios from axios;// 创建axios实例 const instance axios.create();// 设置超时时间 instance.defaults.timeout 5000;// 最大重试次数 cons…...

拉力测试cuda pytorch 把 4070显卡拉满

import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试&#xff0c;通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小&#xff0c;增大可提高计算复杂度duration: 测试持续时间&#xff08;秒&…...

【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)

1.获取 authorizationCode&#xff1a; 2.利用 authorizationCode 获取 accessToken&#xff1a;文档中心 3.获取手机&#xff1a;文档中心 4.获取昵称头像&#xff1a;文档中心 首先创建 request 若要获取手机号&#xff0c;scope必填 phone&#xff0c;permissions 必填 …...

Redis的发布订阅模式与专业的 MQ(如 Kafka, RabbitMQ)相比,优缺点是什么?适用于哪些场景?

Redis 的发布订阅&#xff08;Pub/Sub&#xff09;模式与专业的 MQ&#xff08;Message Queue&#xff09;如 Kafka、RabbitMQ 进行比较&#xff0c;核心的权衡点在于&#xff1a;简单与速度 vs. 可靠与功能。 下面我们详细展开对比。 Redis Pub/Sub 的核心特点 它是一个发后…...

【笔记】WSL 中 Rust 安装与测试完整记录

#工作记录 WSL 中 Rust 安装与测试完整记录 1. 运行环境 系统&#xff1a;Ubuntu 24.04 LTS (WSL2)架构&#xff1a;x86_64 (GNU/Linux)Rust 版本&#xff1a;rustc 1.87.0 (2025-05-09)Cargo 版本&#xff1a;cargo 1.87.0 (2025-05-06) 2. 安装 Rust 2.1 使用 Rust 官方安…...

【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制

使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下&#xff0c;限制某个 IP 的访问频率是非常重要的&#xff0c;可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案&#xff0c;使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...

免费数学几何作图web平台

光锐软件免费数学工具&#xff0c;maths,数学制图&#xff0c;数学作图&#xff0c;几何作图&#xff0c;几何&#xff0c;AR开发,AR教育,增强现实,软件公司,XR,MR,VR,虚拟仿真,虚拟现实,混合现实,教育科技产品,职业模拟培训,高保真VR场景,结构互动课件,元宇宙http://xaglare.c…...

GO协程(Goroutine)问题总结

在使用Go语言来编写代码时&#xff0c;遇到的一些问题总结一下 [参考文档]&#xff1a;https://www.topgoer.com/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine.html 1. main()函数默认的Goroutine 场景再现&#xff1a; 今天在看到这个教程的时候&#xff0c;在自己的电…...

数学建模-滑翔伞伞翼面积的设计,运动状态计算和优化 !

我们考虑滑翔伞的伞翼面积设计问题以及运动状态描述。滑翔伞的性能主要取决于伞翼面积、气动特性以及飞行员的重量。我们的目标是建立数学模型来描述滑翔伞的运动状态,并优化伞翼面积的设计。 一、问题分析 滑翔伞在飞行过程中受到重力、升力和阻力的作用。升力和阻力与伞翼面…...