给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
提示:
1 <= k <= nums.length <= 104
-104 <= nums[i] <= 104
思路1:采用优先级队列的办法,当队列长度大于 k 时,进行出队。当遍历过所有的数字后,对顶即为第 k 个最大的元素。
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for(int num : nums){
heap.offer(num);
if(heap.size() > k){
heap.poll();
}
}
return heap.peek();
}
}
思路2:采用快排的办法。函数 partition 中的变量 first 作为指针1,始终指向最后一个比基准值小的值,循环中的 i 作为第二个指针,当发现有数字比基准值小,则 first 右移一次,交换指针 first 和 i 指向的值。最后再把 first++,进行交换,使得基准值左侧都比基准值小,右侧都比基准值大。
class Solution {
public int findKthLargest(int[] nums, int k) {
int len = nums.length - 1;
int target = len - k + 1;
int start = 0,end = len;
int index = partition(nums,start,end);
while(index != target){
if(index < target){
start = index + 1;
}else{
end = index - 1;
}
index = partition(nums,start,end);
}
return nums[target];
}
public int partition(int[] nums,int start,int end){
Random random = new Random();
int pivot = random.nextInt(end - start + 1) + start;
int first = start - 1;
swap(nums,pivot,end);
for(int i = start ; i < end; i++){
if(nums[i] < nums[end]){
first++;
swap(nums,first,i);
}
}
first++;
swap(nums,end,first);
return first;
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}