https://leetcode.com/problems/kth-largest-element-in-an-array/
解法1:
public int findKthLargest(int[] nums, int k) {
// 排序并且放入大根堆中
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
}
int number = 0;
while(k-- > 0) {
number = queue.poll();
}
//取出第K个
return number;
}
解法2:
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
解法3:
public int findKthLargest(int[] nums, int k) {
//使用小根堆,当堆中数量小于k时,将数据放入堆中,如果当前数大于堆顶的数,则弹出,将当前数放入堆中
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int num : nums) {
if (queue.size() < k) {
queue.offer(num);
} else {
if (num > queue.peek()) {
queue.poll();
queue.offer(num);
}
}
}
return queue.peek();
}
对于算法中常见的PriorityQueue ,它的时间复杂度和实现如下:
Java PriorityQueue Time Complexity
- For enqueing and dequeing methods, the time complexity is O(log(n))
- For the remove(Object) and contains(Object) methods, the time complexity is linear.
- For the retrieval methods, it has constant time complexity.
三种方法适用于不同的内容,例如如果nums的数量和k的数量的相对关系,如果nums数量>>k数量,则方法3较好。