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.
[code]
public class Solution {
public int findKthLargest(int[] nums, int k) {
return kth(nums,0, nums.length-1, k);
}
int kth(int[]nums, int start, int end, int k)
{
int r=nums[end];
int i=start-1, j=start;
while(j<end)
{
if(nums[j]<=r)
{
swap(nums,++i,j++);
}
else j++;
}
swap(nums,++i,end);
if(end-i+1==k)return r;
else if(end-i+1<k)return kth(nums, start, i-1, k-end+i-1);
else return kth(nums, i+1, end, k);
}
void swap(int[] nums, int i ,int j)
{
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
}
}