当前位置:网站首页>力扣(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);
}
};
边栏推荐
- 深度学习(三)分类 理论部分
- db2中kettle报错 Field [XXX] is required and couldn‘t be found 解决方法
- pytorch applied to MNIST handwritten font recognition
- 2022.8.3-----leetcode.899
- 小程序+新零售,玩转行业新玩法!
- 一个属于程序员的七夕节!
- sql注入一般流程(附例题)
- 【翻译】Terraform和Kubernetes的交集
- Taurus.MVC WebAPI 入门开发教程1:框架下载环境配置与运行(含系列目录)。
- 云开发校园微社区微信小程序源码/二手交易/兼职交友微信小程序开源源码
猜你喜欢
cdh6.x 集成spark-sql
Sfdp 超级表单开发平台 V6.0.5 正式发布
2022年T电梯修理考题及答案
C program compilation and predefined detailed explanation
Deep Learning (3) Classification Theory Part
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
ssh服务详解
自制蓝牙手机app控制stm8/stm32/C51板载LED
阿里云国际版基于快照与镜像功能迁移云服务器数据
单片机C语言->的用法,和意思
随机推荐
2022广东省安全员A证第三批(主要负责人)考试题库及模拟考试
Development of Taurus. MVC WebAPI introductory tutorial 1: download environment configuration and operation framework (including series directory).
DHCP服务详解
云开发旅游打卡广场微信小程序源码(含视频教程)
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
0.1 前言
[Original] Start the XPS/OXPS reader that comes with Windows 10
activiti流程执行过程中,数据库表的使用关系
如果禁用了安全启动,GNOME 就会发出警告
STM8S项目创建(STVD创建)---使用 COSMIC 创建 C 语言项目
Zabbix设置邮件告警+企业微信告警
【云原生】DevOps(六):Jenkins流水线
(cf)Codeforces Round #811 (Div. 3)A--E详细题解
Countdown to 2 days, the "New Infrastructure of Cultural Digital Strategy and Ecological Construction of Cultural Art Chain" will kick off soon
STM32-遥感数据处理
一文看懂推荐系统:召回05:矩阵补充、最近邻查找,工业界基本不用了,但是有助于理解双塔模型
【学习笔记之菜Dog学C】动态内存管理
小程序+新零售,玩转行业新玩法!
Asynchronous programming solution Generator generator function, iterator iterator, async/await, Promise
第08章 索引的创建与设计原则【2.索引及调优篇】【MySQL高级】