当前位置:网站首页>力扣(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);
}
};
边栏推荐
猜你喜欢

一文看懂推荐系统:召回05:矩阵补充、最近邻查找,工业界基本不用了,但是有助于理解双塔模型

《nlp入门+实战:第八章:使用Pytorch实现手写数字识别》

云开发旅游打卡广场微信小程序源码(含视频教程)

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

2022焊工(初级)上岗证题目模拟考试平台操作

小程序:扫码打开参数解析

ant-design的Select组件采用自定义后缀图标(suffixIcon属性)时,点击该自定义图标没有反应,不会展示下拉菜单的问题

全网没有之一的JMeter 接口测试流程详解

共n级台阶,每次可以上1级或2级台阶,有多少种上法?

new Date将字符串转化成日期格式 兼容IE,ie8如何通过new Date将字符串转化成日期格式,js中如何进行字符串替换, replace() 方法详解
随机推荐
Small Turtle Compilation Notes
SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
In the season of going overseas, the localization of Internet tips for going overseas
2022年茶艺师(中级)考试试题模拟考试平台操作
How to drop all tables under database in MySQL
STM8S-----option byte
异步编程解决方案 Generator生成器函数、iterator迭代器、async/await、Promise
C language -- ring buffer
How to read the resources files in the directory path?
DHCP服务详解
Brush esp8266-01 s firmware steps
View mysql deadlock syntax
Deep Learning (3) Classification Theory Part
2022焊工(初级)上岗证题目模拟考试平台操作
2022年T电梯修理考题及答案
Security First: Tools You Need to Know to Implement DevSecOps Best Practices
MySQL高级-读写分离-分库分表
【指针内功修炼】深度剖析指针笔试题(三)
多线程间的通信方式你知道几种?
QNX Hypervisor 2.2 user manual] 10.1 gm vdev options