标签:
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.
求一个未排序的数组的第k大的值,其中相同大小的仍然计算大小。并非是不同的第k大的值。
</pre><pre name="code" class="cpp">class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
if(nums.size()==0) return 0;
if(nums.size()==1) return nums[0];
sort(nums.begin(),nums.end());
return nums[nums.size()-k];
}
};class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
if(nums.size()==0) return 0;
if(nums.size()==1) return nums[0];
int low=0,high=nums.size()-1;
while(low<high)
{
int l=low;
int h=high;
int prio=nums[low];
while(l<h)
{
while(l<h&&nums[h]>prio) h--;
swap(nums[h],nums[l]);
while(l<h&&nums[l]<=prio) l++;
swap(nums[h],nums[l]);
}
nums[l]=prio;
if(l==nums.size()-k) return nums[nums.size()-k];
else if(l>nums.size()-(k)) high=l-1;
else
low=l+1;
}
return nums[nums.size()-(k)];
}
};class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
if(nums.size()==0) return 0;
if(nums.size()==1) return nums[0];
int low=0,high=nums.size()-1;
while(low<high)
{
int l=low;
int h=high;
int prio=nums[low];
while(l<h)
{
while(l<h&&nums[h]<prio) h--;
swap(nums[h],nums[l]);
while(l<h&&nums[l]>=prio) l++;
swap(nums[h],nums[l]);
}
nums[l]=prio;
if(l==k-1) return nums[k-1];
else if(l>k-1) high=l-1;
else
low=l+1;
}
return nums[k - 1];
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
Kth Largest Element in an Array
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/47211225