题目链接:https://leetcode.com/problems/kth-largest-element-in-an-array/
题目:
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.
解题思路:
这题的考点是排序。题目给的线索是Heap。
最简单的方法是使用库函数 Arrays.sort() 对数组进行快速排序,获取有序数组的倒数第 K 个元素即可。
其实,自己一开始能想到的是堆排序。题目提示也是 heap。
但,在网上看到别人的做法是使用快速排序,当 pivot 放入倒数第 K 个位置时,当前 pivot 即为第 K 大的元素,排序终止。
再上网查,发现有人用优先队列(最小堆)来求解。
遍历数组时将数字加入优先队列(堆),一旦堆的大小大于k就将堆顶元素去除,确保堆的大小为k。遍历完后堆顶就是返回值。
我想,这种方法才是题目所要考的吧。
参考链接:https://segmentfault.com/a/1190000003704825
代码实现:
使用优先队列:
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> p = new PriorityQueue<Integer>();
for(int i = 0 ; i < nums.length; i++){
p.add(nums[i]);
if(p.size()>k) p.poll();
}
return p.poll();
}
}
31 / 31 test cases passed.
Status: Accepted
Runtime: 16 ms
使用库函数:
public class Solution {
public int findKthLargest(int[] nums, int k) {
if(nums == null || nums.length == 0)
return 0;
Arrays.sort(nums);
return nums[nums.length - k];
}
}
31 / 31 test cases passed.
Status: Accepted
Runtime: 4 ms
使用快速排序:
public class Solution {
public int findKthLargest(int[] nums, int k) {
if(nums == null || nums.length == 0)
return 0;
return getKth(nums.length - k, nums, 0, nums.length - 1);
}
int getKth(int k, int[] nums, int start, int end) {
int l = start;
int r = end;
int pivot = nums[l];
while(l < r) {
while(l < r && nums[r] >= pivot) {
r --;
}
nums[l] = nums[r];
while(l < r && nums[l] <= pivot) {
l ++;
}
nums[r] = nums[l];
}
nums[l] = pivot;
if(l == k) { // l 为此时 pivot 的位置
return pivot;
} else if(l < k) { // k 在 此时 pivot 的右侧,对 pivot(l)进行快速排序
return getKth(k, nums, l + 1, end);
} else { // k 在 此时 pivot 的左侧侧,对 pivot(r)进行快速排序
return getKth(k, nums, start, r - 1);
}
}
}
31 / 31 test cases passed.
Status: Accepted
Runtime: 52 ms