您的位置:首页 > 编程语言 > C语言/C++

LeetCode-Kth Largest Element in an Array-解题报告

2015-06-29 23:15 591 查看
原链接https://leetcode.com/problems/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.

For example,

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.

类似快速排序,选取第一个元素作为分界元素,快速排序后

s...i...e

如果i - s + 1 == k return nums[i]

如果i-s + 1 > k return find_k_largest(nums, k, s, i - 1);

其他情况 return  find_k_largest(nums, k - (i - s + 1), i + 1, e);

当然了你也可以随机选取一个元素作为参考元素

<span style="font-size:14px;">class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return find_k_largest(nums, k, 0, nums.size() - 1);
}
int find_k_largest(vector<int>& nums, int k, int s, int e)
{
int i = s, j = e, tmp = nums[i];
while (i < j)
{
while (i < j && nums[j] <= tmp)--j;
nums[i] = nums[j];
while (i < j && nums[i] > tmp)++i;
nums[j] = nums[i];
}
nums[i] = tmp;

if (i - s + 1 == k)return nums[i];
else if(i - s + 1 > k)return find_k_largest(nums, k, s, i - 1);
else return find_k_largest(nums, k - (i - s + 1), i + 1, e);
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode