【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是实现底层堆的容器,必须是数组实现的容器,如vector、dequeFunctional是比较方式/比较函数/优先级 priority_queue<Type>…...
typescript 中的泛型
泛型:解决 类、接口、方法的复用性、以及对不特定数据类型的支持 传入的参数与返回参数类型一致 泛型函数 // T表示泛型,具体什么类型是调用这个方法的时候决定的 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.软件下载:DCloud - HBuilder、HBuilderX、uni-app、uniapp、5、5plus、mui、wap2app、流应用、HTML5、小程序开发、跨平台App、多端框架 2.软件介绍 HBuilder是由DCloud(数字天堂)推出的一款面向HTML5的Web开发…...
vue3 + ts实现canvas绘制的waterfall
实际运行效果(仅包含waterfall图表部分) component.vue <template><div ref"heatmap" :style"{ height: props.containerHeight px }" /> </template><script setup> import ColorMap from "color…...
代码随想录算法训练营第四十四天
sad的一天,明天开始上班,而且娃还行,媳妇儿状态不稳定,太难了也!!! 完全背包 #include<vector> #include<iostream> using namespace::std; int main(){int N;//种类int V;//空间ci…...
【3dmax笔记】027:配置修改器集、工具栏自定义与加载
文章目录 一、配置修改器集二、自定义工具栏三、加载工具栏 一、配置修改器集 可以把自己常用的修改命令放到右边框中的部分,便于自己的操作,省去了每次都要花半天时间找命令的尴尬。新建一个二维或者三维物体,点击修改面板,点击…...
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.…...
内存卡罢工,数据危机?别急,有救!
在日常生活和工作中,我们越来越依赖于各种电子设备来存储重要数据。其中,内存卡因其便携性和大容量而广受欢迎。然而,当内存卡突然损坏打不开时,我们该如何应对?本文将为您详细解析这一问题,并提供有效的解…...
python爬虫实战
import requests import json yesinput(输入页数:) 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 的标记性语言。它强调以数据为中心,并不是以标识语言为重点例如 SpringBoot 的配置文件 application.yml 也是一个 yaml 格式的文件 语法格式 通过缩进表示层级关系不能使用tab进行缩进&am…...
mac系统安装steam报错-解决办法
今天给虚拟机装了个苹果系统,然后想装个steam,从steam的官方下载安装steam_osx.dmg时,总是报“steam_osx已损坏,无法打开,请移动到废纸篓“。搜了一下找到了解决办法,这里记录一下。 双击steam_osx.dmg时&…...
这个簇状柱形图怎么添加百分比?
这个图表是excel默认的图表配色,有的人做出来都那个百分比,一起来做一个这样的图表。 1.插入图表 选中数据区域,点击 插入选项卡,在图表那一栏,点一下柱形图右侧那个倒三角,在弹邮对话框中,选…...
Tomact安装配置及使用(超详细)
文章目录 web相关知识概述web简介(了解)软件架构模式(掌握)BS:browser server 浏览器服务器CS: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文件,如何单独运行某个文件?n…...
使用request-try-notifyState流程实现UI控制与状态反馈的完整闭环
1. 前言 在Qt编程时,我们经常会在界面上添加一些按钮,当按钮被点击时,执行某段代码,例如显示一个对话框、关闭窗口,保存文件等等。 这种由UI控件触发某种信号,通过信号槽触发目的代码执行的场景非常多。这…...
屏蔽罩材质和厚度对屏蔽效能的影响
一.屏蔽效能的影响因素 屏蔽效能的影响因素主要有两个方面:屏蔽材料的特性和厚度;如下图所示,电磁波经过不同媒介时,会在分界面形成反射,穿过界面的电磁波一部分被反射回去,这部分能量损失…...
Qt简单离线音乐播放器
有上传本地音乐文件,播放,暂停,拖拉进度条等功能的播放器。 mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QMediaPlayer> #include <QFileDialog> #include <QTime&g…...
微信小程序常用的api
基础API: wx.request:用于发起网络请求,支持GET、POST等方式,是获取网络数据的主要手段。wx.showToast:显示消息提示框,通常用于向用户展示操作成功、失败或加载中等状态。wx.showModal:显示模态…...
Docker 离线安装指南
参考文章 1、确认操作系统类型及内核版本 Docker依赖于Linux内核的一些特性,不同版本的Docker对内核版本有不同要求。例如,Docker 17.06及之后的版本通常需要Linux内核3.10及以上版本,Docker17.09及更高版本对应Linux内核4.9.x及更高版本。…...
进程地址空间(比特课总结)
一、进程地址空间 1. 环境变量 1 )⽤户级环境变量与系统级环境变量 全局属性:环境变量具有全局属性,会被⼦进程继承。例如当bash启动⼦进程时,环 境变量会⾃动传递给⼦进程。 本地变量限制:本地变量只在当前进程(ba…...
vscode(仍待补充)
写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh? debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...
LeetCode - 394. 字符串解码
题目 394. 字符串解码 - 力扣(LeetCode) 思路 使用两个栈:一个存储重复次数,一个存储字符串 遍历输入字符串: 数字处理:遇到数字时,累积计算重复次数左括号处理:保存当前状态&a…...
电脑插入多块移动硬盘后经常出现卡顿和蓝屏
当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时,可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案: 1. 检查电源供电问题 问题原因:多块移动硬盘同时运行可能导致USB接口供电不足&#x…...
在 Nginx Stream 层“改写”MQTT ngx_stream_mqtt_filter_module
1、为什么要修改 CONNECT 报文? 多租户隔离:自动为接入设备追加租户前缀,后端按 ClientID 拆分队列。零代码鉴权:将入站用户名替换为 OAuth Access-Token,后端 Broker 统一校验。灰度发布:根据 IP/地理位写…...
【Go】3、Go语言进阶与依赖管理
前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课,做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程,它的核心机制是 Goroutine 协程、Channel 通道,并基于CSP(Communicating Sequential Processes࿰…...
全志A40i android7.1 调试信息打印串口由uart0改为uart3
一,概述 1. 目的 将调试信息打印串口由uart0改为uart3。 2. 版本信息 Uboot版本:2014.07; Kernel版本:Linux-3.10; 二,Uboot 1. sys_config.fex改动 使能uart3(TX:PH00 RX:PH01),并让boo…...
图表类系列各种样式PPT模版分享
图标图表系列PPT模版,柱状图PPT模版,线状图PPT模版,折线图PPT模版,饼状图PPT模版,雷达图PPT模版,树状图PPT模版 图表类系列各种样式PPT模版分享:图表系列PPT模板https://pan.quark.cn/s/20d40aa…...
以光量子为例,详解量子获取方式
光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学(silicon photonics)的光波导(optical waveguide)芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中,光既是波又是粒子。光子本…...
