当前位置:网站首页>力扣(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);
}
};
边栏推荐
- 2022年T电梯修理考题及答案
- Returns the maximum number of palindromes in a string
- 安装postgis时报找不到“POSTGIS_VERSION”这个函数
- MallBook 助力SKT思珂特教育集团,立足变化,拥抱敏捷交易
- 一文看懂推荐系统:召回05:矩阵补充、最近邻查找,工业界基本不用了,但是有助于理解双塔模型
- 阿里云国际版基于快照与镜像功能迁移云服务器数据
- Simple record of Flink principle flow chart
- 系统太多,多账号互通如何实现?
- 参加Oracle OCP和MySQL OCP考试的学员怎样在VUE预约考试
- Pine Script | How to display and typeset a plot switch?
猜你喜欢

Pine脚本 | 如何显示和排版绘图开关?

Qt中对象树的机制介绍以及底层实现,各种结果分析:(以及自己写容易犯错的点)

Development of Taurus. MVC WebAPI introductory tutorial 1: download environment configuration and operation framework (including series directory).

Parquet encoding

APP电商如何快速分润分账?

Rongyun "Audio and Video Architecture Practice" technical session [complete PPT included]

云开发校园微社区微信小程序源码/二手交易/兼职交友微信小程序开源源码

出海季,互联网出海锦囊之本地化

Detailed analysis of scaffolding content

activiti流程执行过程中,数据库表的使用关系
随机推荐
Ant - the design of the Select component using a custom icon (suffixIcon attribute) suffixes, click on the custom ICONS have no reaction, will not display the drop-down menu
MySQL 查询练习(1)
Parquet encoding
一个属于程序员的七夕节!
SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
QNX Hypervisor 2.2 user manual] 10.1 gm vdev options
云开发旅游打卡广场微信小程序源码(含视频教程)
tkmapper的crud示例:
Countdown to 2 days, the "New Infrastructure of Cultural Digital Strategy and Ecological Construction of Cultural Art Chain" will kick off soon
pytorch应用于MNIST手写字体识别
Brush esp8266-01 s firmware steps
In the season of going overseas, the localization of Internet tips for going overseas
esp8266-01s刷固件步骤
案例 | 重庆银行流动数据安全挑战及应对实践
[QNX Hypervisor 2.2用户手册]10.3 vdev gic
安装postgis时报找不到“POSTGIS_VERSION”这个函数
View mysql deadlock syntax
How to read the resources files in the directory path?
编写 BOLL 心得体会
Security First: Tools You Need to Know to Implement DevSecOps Best Practices