Leetcode 215. Kth Largest Element in an Array
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.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
题目大意:在乱序的数组中找到第k大的数,注意是该数组排序后的第k个数字而不是第k个大的单独的数字。
解题思路:将数组由大到小排序,返回第k-1个数字。时间复杂度O(nlogn)。
代码说明:代码1直接调用sort函数耗时8ms。代码2自写快排,规定第一个元素为哨兵项耗时80ms。可以看出STL的优化还是很强大的。
代码1:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
return nums[nums.size() - k];
}
};
代码2:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left = 0, right = nums.size() - 1;
while(true)
{
int idx = partition(nums, left, right);
if(idx == k - 1)
return nums[idx];
if(idx > k - 1)
right = idx - 1;
else
left = idx + 1;
}
return -1;
}
private:
int partition(vector<int>& nums, int left, int right){
int temp = nums[left], l = left + 1, r = right;
while(l <= r)
{
if(nums[l] < temp && nums[r] > temp)
swap(nums[l++], nums[r--]);
if(nums[l] >= temp)
l++;
if(nums[r] <= temp)
r--;
}
swap(nums[left], nums[r]);
return r;
}
};
本文介绍了解决LeetCode 215题“数组中的第K个最大元素”的两种方法。一种是使用STL的sort函数,时间复杂度为O(nlogn),另一种是自写快速排序算法,时间复杂度相同但实际运行时间较长。文章提供了详细的代码实现及性能对比。
887

被折叠的 条评论
为什么被折叠?



