LeetCode problem#215
Kth Largest Element in an Array
Solved in 1 languageJava
Solution
26 lines
1class Solution {
2 // time O(n log n)
3 public int findKthLargest(int[] nums, int k) {
4 Arrays.sort(nums);
5
6 return nums[nums.length - k];
7 }
8}
9
10// using max heap
11// class Solution {
12// public int findKthLargest(int[] nums, int k) {
13// PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
14
15// for (int i = 0; i < nums.length; i++) {
16// maxHeap.add(nums[i]);
17// }
18
19// // int kthLargest = 0;
20// for (int i = 1; i < k; i++) {
21// maxHeap.remove();
22// }
23
24// return maxHeap.peek();
25// }
26// }Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.