Find the k th 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.
public class Solution { public int findKthLargest( int [] nums, int k) { if (k>nums.length) return 0 ; int mid = partion(nums, 0 , nums.length- 1 ); while (mid!=k- 1 ){ if (mid>k- 1 ){ mid = partion(nums, 0 , mid- 1 ); }else { mid = partion(nums, mid+1 , nums.length- 1 ); } } return nums[mid]; } int partion( int [] nums, int start, int end){ int t = nums[start]; while (start<end){ while (start<end&&nums[end]<=t){ end--; } nums[start] = nums[end]; while (start<end&&nums[start]>=t){ start++; } nums[end] = nums[start]; } nums[start] = t; return start; } }
原文链接http://blog.csdn.net/crazy__chen/article/details/46581419