Leetcode / 215. Kth Largest Element in an Array
Pick a programming language:
Here is the source code for the solution to this problem.
class Solution {
// time O(n log n)
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}
// using max heap
// class Solution {
// public int findKthLargest(int[] nums, int k) {
// PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
// for (int i = 0; i < nums.length; i++) {
// maxHeap.add(nums[i]);
// }
// // int kthLargest = 0;
// for (int i = 1; i < k; i++) {
// maxHeap.remove();
// }
// return maxHeap.peek();
// }
// }
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: