【LeetCode 215】Kth Largest Element in an Array

时间:2021-08-28 12:19:29

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.

思路:

依据时间和空间复杂度,有多种方法。这里给出易于实现,基本能够满足面试、笔试要求的类似于快速排序的(递归)实现。

class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
vector<int> leftvec;
vector<int> rightvec; //以nums[0]作为分界元素,从nums[1]开始遍历
//比nums[0]小的元素放入leftvec,反之放入rightvec
for(int i = ; i < nums.size(); i++)
{
if(nums[i] <= nums[])
leftvec.push_back(nums[i]);
else
rightvec.push_back(nums[i]);
} //rightvec的长度即为大于nums[0]的元素的个数
int len = rightvec.size(); if(len >= k)//前k大的元素都在rightvec中,递归求解rightvec
{
return findKthLargest(rightvec, k);
}
else if(len == k - )//比nums[0]大的元素有k-1个,那么nums[0]即为所求结果
{
return nums[];
}
else//比nums[0]大的元素有[0, k-2]个,说明第K大的元素在leftvec中,递归求解leftvec
{
return findKthLargest(leftvec, k - len - );
}
}
};