当前位置:网站首页>Power button (LeetCode) 215. The first K largest elements in the array (2022.08.03)
Power button (LeetCode) 215. The first K largest elements in the array (2022.08.03)
2022-08-04 03:03: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);
}
};
边栏推荐
- STM8S105K4T6------Serial port sending and receiving
- ant-design的Select组件采用自定义后缀图标(suffixIcon属性)时,点击该自定义图标没有反应,不会展示下拉菜单的问题
- Parquet encoding
- STM8S105k4t6c--------------点亮LED
- Utilities of Ruineng Micrometer Chip RN2026
- 织梦响应式酒店民宿住宿类网站织梦模板(自适应手机端)
- Engineering drawing review questions (with answers)
- 逻辑漏洞----其他类型
- 移动端响应式适配的方法
- JVM内存和垃圾回收-07.堆
猜你喜欢

小程序+新零售,玩转行业新玩法!

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

Example 039: Inserting elements into an ordered list

架构实战营模块三作业

Dong mingzhu live cold face away, when employees frequency low-level mistakes, no one can understand their products

cdh6.x 集成spark-sql

关联接口测试

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

第08章 索引的创建与设计原则【2.索引及调优篇】【MySQL高级】

Polygon zkEVM网络节点
随机推荐
Sfdp 超级表单开发平台 V6.0.5 正式发布
瑞能微计量芯片RN2026的实用程序
mpf5_定价Bond_yield curve_Spot coupon_duration_有效利率_连续复利_远期_Vasicek短期_CIR模型Derivatives_Tridiagonal_ppf
2022年茶艺师(中级)考试试题模拟考试平台操作
Example 041: Methods and variables of a class
esp8266-01s刷固件步骤
activiti流程执行过程中,数据库表的使用关系
Mini program + new retail, play the new way of playing in the industry!
自制蓝牙手机app控制stm8/stm32/C51板载LED
在更一般意义上验算移位距离和假设
yum 仅下载包
《nlp入门+实战:第八章:使用Pytorch实现手写数字识别》
Deep Learning (3) Classification Theory Part
Exclude_reserved_words 排除关键字
案例 | 重庆银行流动数据安全挑战及应对实践
阿里云国际版基于快照与镜像功能迁移云服务器数据
QNX Hypervisor 2.2用户手册]10.2 vdev 8259
MallBook 助力SKT思珂特教育集团,立足变化,拥抱敏捷交易
There are too many systems, how to realize multi-account interworking?
tkmapper的crud示例: