当前位置:网站首页>力扣(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);
}
};
边栏推荐
- pytorch应用于MNIST手写字体识别
- Detailed analysis of scaffolding content
- web端动效 lottie-web 使用
- 【Playwright测试教程】5分钟上手
- yum 仅下载包
- In a more general sense, calculating the displacement distance and assumptions
- In the season of going overseas, the localization of Internet tips for going overseas
- 【观察】超聚变:首提“算网九阶”评估模型,共建开放繁荣的算力网络
- 各位大佬好,麻烦问一下flink cdc oracle写入doris的时候,发现cpu异常,一下下跑
- P3384 【模板】轻重链剖分/树链剖分
猜你喜欢

Architecture of the actual combat camp module three operations

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

esp8266-01s刷固件步骤

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

【云原生】DevOps(六):Jenkins流水线

C language -- ring buffer

阿里云国际版基于快照与镜像功能迁移云服务器数据

一个属于程序员的七夕节!

How to drop all tables under database in MySQL

Qt中对象树的机制介绍以及底层实现,各种结果分析:(以及自己写容易犯错的点)
随机推荐
一个属于程序员的七夕节!
docker+网桥+redis主从+哨兵模式
sql注入一般流程(附例题)
Mini program + new retail, play the new way of playing in the industry!
cdh6.x 集成spark-sql
参加Oracle OCP和MySQL OCP考试的学员怎样在VUE预约考试
Security First: Tools You Need to Know to Implement DevSecOps Best Practices
创新互融|华秋赋能助力OpenHarmony生态硬件开发落地
异步编程解决方案 Generator生成器函数、iterator迭代器、async/await、Promise
Deep Learning (3) Classification Theory Part
Architecture of the actual combat camp module three operations
0.1 前言
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
Pine Script | How to display and typeset a plot switch?
yum 仅下载包
查看mysql死锁语法
TOML配置文件格式,YAML最有力的竞争者
Utilities of Ruineng Micrometer Chip RN2026
STM8S105K4T6------Serial port sending and receiving
(cf)Codeforces Round #811 (Div. 3)A--E详细题解