当前位置:网站首页>力扣(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);
}
};
边栏推荐
- QNX Hypervisor 2.2用户手册]10.1 通用vdev选项
- DHCP服务详解
- 倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
- 怎样提高网络数据安全性
- tkmapper的crud示例:
- LeetCode:899. 有序队列【思维题】
- Qt中对象树的机制介绍以及底层实现,各种结果分析:(以及自己写容易犯错的点)
- There are n steps in total, and you can go up to 1 or 2 steps each time. How many ways are there?
- STM8S项目创建(STVD创建)---使用 COSMIC 创建 C 语言项目
- unsafe.Pointer, pointer, reference in golang
猜你喜欢

【学习笔记之菜Dog学C】动态内存管理

Countdown to 2 days, the "New Infrastructure of Cultural Digital Strategy and Ecological Construction of Cultural Art Chain" will kick off soon

MySQL高级-读写分离-分库分表

docker+网桥+redis主从+哨兵模式

uni-app 从零开始-基础模版(一)

Brush esp8266-01 s firmware steps

There are n steps in total, and you can go up to 1 or 2 steps each time. How many ways are there?

C language -- ring buffer

系统太多,多账号互通如何实现?

如果禁用了安全启动,GNOME 就会发出警告
随机推荐
阿里云国际版基于快照与镜像功能迁移云服务器数据
sqoop ETL工具
Zabbix设置邮件告警+企业微信告警
自制蓝牙手机app控制stm8/stm32/C51板载LED
深度学习(三)分类 理论部分
SQL注入中 #、 --+、 --%20、 %23是什么意思?
如何在MySQL中的数据库下删除所有的表
How many ways do you know about communication between multiple threads?
Detailed analysis of scaffolding content
Deep Learning (3) Classification Theory Part
STM8S105k4t6c---------------Light up LED
验证码业务逻辑漏洞
共n级台阶,每次可以上1级或2级台阶,有多少种上法?
[QNX Hypervisor 2.2 User Manual] 10.3 vdev gic
数据安全峰会2022 | 美创DSM获颁“数据安全产品能力验证计划”评测证书
TOML配置文件格式,YAML最有力的竞争者
flinkcdc 消费 mysql binlog 没有 sqltype=delete 的数据是什么原
2022年最新海南建筑八大员(材料员)模拟考试试题及答案
Polygon zkEVM网络节点
瑞能微计量芯片RN2026的实用程序