当前位置:网站首页>Power button (LeetCode) 215. The first K largest elements in the array (2022.08.03)
Power button (LeetCode) 215. The first K largest elements in the array (2022.08.03)
2022-08-04 03:03:00 【ChaoYue_miku】
给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素.
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素.
示例 1:
输入: [3,2,1,5,6,4], k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6], k = 4
输出: 4
提示:
1 <= k <= nums.length <= 105
-104 <= nums[i] <= 104
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/kth-largest-element-in-an-array
方法一:快速排序
C++提交内容:
class Solution {
public:
int quickSelect(vector<int>& a, int l, int r, int index) {
int q = randomPartition(a, l, r);
if (q == index) {
return a[q];
} else {
return q < index ? quickSelect(a, q + 1, r, index) : quickSelect(a, l, q - 1, index);
}
}
inline int randomPartition(vector<int>& a, int l, int r) {
int i = rand() % (r - l + 1) + l;
swap(a[i], a[r]);
return partition(a, l, r);
}
inline int partition(vector<int>& a, int l, int r) {
int x = a[r], i = l - 1;
for (int j = l; j < r; ++j) {
if (a[j] <= x) {
swap(a[++i], a[j]);
}
}
swap(a[i + 1], a[r]);
return i + 1;
}
int findKthLargest(vector<int>& nums, int k) {
srand(time(0));
return quickSelect(nums, 0, nums.size() - 1, nums.size() - k);
}
};
边栏推荐
猜你喜欢
【观察】超聚变:首提“算网九阶”评估模型,共建开放繁荣的算力网络
There are n steps in total, and you can go up to 1 or 2 steps each time. How many ways are there?
DIY电工维修如何拆卸和安装开关面板插座
Why use Selenium for automated testing
董明珠直播时冷脸离场,员工频犯低级错误,自家产品没人能弄明白
docker+网桥+redis主从+哨兵模式
STM8S105K4T6------串口发送和接收
如果禁用了安全启动,GNOME 就会发出警告
Polygon zkEVM网络节点
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
随机推荐
MallBook联合人民交通出版社,推动驾培领域新发展,开启驾培智慧交易新生态
There are n steps in total, and you can go up to 1 or 2 steps each time. How many ways are there?
Example 041: Methods and variables of a class
mpf5_定价Bond_yield curve_Spot coupon_duration_有效利率_连续复利_远期_Vasicek短期_CIR模型Derivatives_Tridiagonal_ppf
SQL注入中 #、 --+、 --%20、 %23是什么意思?
QNX Hypervisor 2.2用户手册]10.2 vdev 8259
cdh6.x 集成spark-sql
STM8S105k4t6c--------------点亮LED
C language -- ring buffer
QNX Hypervisor 2.2 user manual] 10.1 gm vdev options
Development of Taurus. MVC WebAPI introductory tutorial 1: download environment configuration and operation framework (including series directory).
全网没有之一的JMeter 接口测试流程详解
P3384 【模板】轻重链剖分/树链剖分
案例 | 重庆银行流动数据安全挑战及应对实践
sudo 权限控制,简易
View mysql deadlock syntax
0.1 前言
【原创】启动Win10自带的XPS/OXPS阅读器
uni-app 从零开始-基础模版(一)
LeetCode每日一题(2285. Maximum Total Importance of Roads)