【数组】Leetcode编程题解:215. Kth Largest Element in an Array Add to List
来源:互联网 发布:小米任我行 联通网络 编辑:程序博客网 时间:2024/06/07 09:24
题目:Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
样例:
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
这道题我用的是常规方法。先将数组从大到小进行排列,然后输出第k个数,也就是数组中的第k - 1个数。
提交代码:
class Solution {
public:
int findKthLargest(vector< int >& nums, int k) {
for(int i = 0; i < nums.size(); i++) {
for(int j = 0; j < nums.size() - 1; j++) {
if(nums[j] < nums[j + 1])
swap(nums[j], nums[j + 1]);
}
}
return nums[k - 1];
}
};
这种方法的时间复杂度为O(n^2),如果数组中的数字较多,时间会比较长。以下还摘抄了网上其他人的解法:
class Solution {
public:
int findKthLargest(vector< int >& nums, int k) {
int length = nums.size();
if (length == 1) {
return nums[0];
}
vector< int > left;
vector< int > right;
for (int index=1; index<length; index++) { if (nums[index] > nums[0]) { right.push_back(nums[index]); }else{ left.push_back(nums[index]); } } length = right.size(); if (length >=k) { return findKthLargest(right, k); }else if(length == k-1){ return nums[0]; }else{ return findKthLargest(left, k-length-1); }}
};
这种方法极大的缩短了寻找的时间。不用每一次都从头开始遍历数组。或者直接调用sort进行排序,然后用reverse反转过来。
class Solution {
public:
int findKthLargest(vector< int >& nums, int k) {
sort(nums.begin(), nums.end());
reverse(nums.begin(), nums.end());
return nums[k-1];
}
};
- 【数组】Leetcode编程题解:215. Kth Largest Element in an Array Add to List
- Leetcode--Add to List 215. Kth Largest Element in an Array
- LeetCode题解–215. Kth Largest Element in an Array
- LeetCode题解系列--215. Kth Largest Element in an Array
- LeetCode 题解(120): Kth Largest Element in an Array
- LeetCode题解——Kth Largest Element in an Array
- 题解:Kth Largest Element in an Array
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- 死锁的解除
- Apache Mina(二)
- caffe的二分类微调,制作train.txt,val.txt
- 腾讯Bugly热更新集成总结
- SpringMVC multipart文件上传详细教程之三:视图及运行结果
- 【数组】Leetcode编程题解:215. Kth Largest Element in an Array Add to List
- 微信开发.Net 接入示例
- The battery cannot be identified the system will be unable to charge this battery
- JSP 九大隐式对象及其out对象
- MyBatis Generator generatorConfig.xml配置详解
- sox 获取wav文件的时长
- jquery 数值输入框实现
- C#设计模式--装饰器模式
- “没拿到一毛钱股份的老公”刷爆朋友圈 吃瓜群众雾里看花