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.
类似快排,将数组分为两个部分,
public class Solution {
public int findKthLargest(int[] nums, int k) {
int i=0,j=nums.length-1;
k=nums.length-k+1;
while(true){
int center=helper(nums,i,j);
if(center+1==k) return nums[center];
else if(center+1<k){
i=center+1;
}
else {
j=center-1;
}
}
}
public void swap(int[] nums,int a,int b){
int swap=nums[a];
nums[a]=nums[b];
nums[b]=swap;
return;
}
public int helper(int[] nums,int start,int end){
if(start==end) return start;
int i=start,index=end,j=index-1;
while(i<=j){
while(nums[i]<nums[index]) i++;
while(j>=start&&nums[j]>=nums[index]) j--;
if(i<j) swap(nums,i,j);
}
if(i<index)
swap(nums,i,index);
return i;
}
}
用一个优先队列,只存5个数,依次将最小的数抛出。
public int findKthLargest(int[] nums, int k) {
final PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int val : nums) {
pq.offer(val);
if(pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}