Find the kth largest element in an unsorted array. Note that it was the kth largest element in the sorted order and not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k are always valid, 1≤k≤array ' s length.
The simplest idea: sort first, then count down k elements
Complexity of Time: O (NLOGN)
Public class Solution { publicint findkthlargest (intint k) { Arrays.sort (nums); return nums[nums.length-K];} }
Optimization: The thought of partition in Quicksort
Just like Quickselect, the time complexity should be O (n)
Public classSolution { Public intFindkthlargest (int[] Nums,intk) {returnHelper (nums, 0, Nums.length-1, K); } Public intHelperint[] Nums,intLointHiintk) {//if (lo = hi)//return Nums[lo]; intPartition =Nums[lo]; intj =Hi; for(inti = lo+1; I <=J;) { while(I <= hi && nums[i] < partition) i++; while(J >= Lo && nums[j] > Partition) j--; if(I <=j) {Swap (Nums, I, J); I++; j--; }} Swap (Nums, J, Lo); if(k = = hi-j + 1) returnNums[j]; if(K < Hi-j + 1) returnHelper (Nums, J + 1, Hi, k); Else returnHelper (Nums, lo, j-1, K-(Hi-j + 1)); } Public voidSwapint[] Nums,intIintj) {inttemp =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=temp; }}
2015-10-21
Leetcode 215:kth largest Element in an Array