当前位置:网站首页>力扣(LeetCode)215. 数组中的第K个最大元素(2022.08.03)
力扣(LeetCode)215. 数组中的第K个最大元素(2022.08.03)
2022-08-04 03:02: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);
}
};
边栏推荐
- Pine Script | How to display and typeset a plot switch?
- STM8S project creation (STVD creation) --- use COSMIC to create a C language project
- 参加Oracle OCP和MySQL OCP考试的学员怎样在VUE预约考试
- Zabbix set up email alert + enterprise WeChat alert
- 说说数据治理中常见的20个问题
- 董明珠直播时冷脸离场,员工频犯低级错误,自家产品没人能弄明白
- Engineering drawing review questions (with answers)
- web端动效 lottie-web 使用
- STM8S105K4T6------Serial port sending and receiving
- 2022.8.3-----leetcode.899
猜你喜欢
随机推荐
复制带随机指针的链表
Detailed analysis of scaffolding content
In a more general sense, calculating the displacement distance and assumptions
一文看懂推荐系统:召回05:矩阵补充、最近邻查找,工业界基本不用了,但是有助于理解双塔模型
WPE详细教程
View mysql deadlock syntax
kingbaseES V8R2/R3 表在指定表空间,为何显示为默认表空间?
QNX Hypervisor 2.2用户手册]10.1 通用vdev选项
【项目实现】Boost搜索引擎
STM8S105K4T6------Serial port sending and receiving
Utilities of Ruineng Micrometer Chip RN2026
2022G1工业锅炉司炉考试练习题及模拟考试
Good bosses, please ask the flink CDC oracle to Doris, found that the CPU is unusual, a run down
Development of Taurus. MVC WebAPI introductory tutorial 1: download environment configuration and operation framework (including series directory).
Example 041: Methods and variables of a class
【Playwright测试教程】5分钟上手
STM8S105K4T6------串口发送和接收
[QNX Hypervisor 2.2用户手册]10.3 vdev gic
【观察】超聚变:首提“算网九阶”评估模型,共建开放繁荣的算力网络
ssh服务详解









