【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:显示模态…...
深度学习在微纳光子学中的应用
深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向: 逆向设计 通过神经网络快速预测微纳结构的光学响应,替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…...
解决Ubuntu22.04 VMware失败的问题 ubuntu入门之二十八
现象1 打开VMware失败 Ubuntu升级之后打开VMware上报需要安装vmmon和vmnet,点击确认后如下提示 最终上报fail 解决方法 内核升级导致,需要在新内核下重新下载编译安装 查看版本 $ vmware -v VMware Workstation 17.5.1 build-23298084$ lsb_release…...
Spring AI 入门:Java 开发者的生成式 AI 实践之路
一、Spring AI 简介 在人工智能技术快速迭代的今天,Spring AI 作为 Spring 生态系统的新生力量,正在成为 Java 开发者拥抱生成式 AI 的最佳选择。该框架通过模块化设计实现了与主流 AI 服务(如 OpenAI、Anthropic)的无缝对接&…...
uniapp中使用aixos 报错
问题: 在uniapp中使用aixos,运行后报如下错误: AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...
【论文阅读28】-CNN-BiLSTM-Attention-(2024)
本文把滑坡位移序列拆开、筛优质因子,再用 CNN-BiLSTM-Attention 来动态预测每个子序列,最后重构出总位移,预测效果超越传统模型。 文章目录 1 引言2 方法2.1 位移时间序列加性模型2.2 变分模态分解 (VMD) 具体步骤2.3.1 样本熵(S…...
AI书签管理工具开发全记录(十九):嵌入资源处理
1.前言 📝 在上一篇文章中,我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源,方便后续将资源打包到一个可执行文件中。 2.embed介绍 🎯 Go 1.16 引入了革命性的 embed 包,彻底改变了静态资源管理的…...
代码随想录刷题day30
1、零钱兑换II 给你一个整数数组 coins 表示不同面额的硬币,另给一个整数 amount 表示总金额。 请你计算并返回可以凑成总金额的硬币组合数。如果任何硬币组合都无法凑出总金额,返回 0 。 假设每一种面额的硬币有无限个。 题目数据保证结果符合 32 位带…...
C++:多态机制详解
目录 一. 多态的概念 1.静态多态(编译时多态) 二.动态多态的定义及实现 1.多态的构成条件 2.虚函数 3.虚函数的重写/覆盖 4.虚函数重写的一些其他问题 1).协变 2).析构函数的重写 5.override 和 final关键字 1&#…...
莫兰迪高级灰总结计划简约商务通用PPT模版
莫兰迪高级灰总结计划简约商务通用PPT模版,莫兰迪调色板清新简约工作汇报PPT模版,莫兰迪时尚风极简设计PPT模版,大学生毕业论文答辩PPT模版,莫兰迪配色总结计划简约商务通用PPT模版,莫兰迪商务汇报PPT模版,…...
认识CMake并使用CMake构建自己的第一个项目
1.CMake的作用和优势 跨平台支持:CMake支持多种操作系统和编译器,使用同一份构建配置可以在不同的环境中使用 简化配置:通过CMakeLists.txt文件,用户可以定义项目结构、依赖项、编译选项等,无需手动编写复杂的构建脚本…...
