-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKthLargestElementInArray.java
More file actions
37 lines (28 loc) · 924 Bytes
/
KthLargestElementInArray.java
File metadata and controls
37 lines (28 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 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.
// See: https://leetcode.com/problems/kth-largest-element-in-an-array/
package leetcode.others;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
public class KthLargestElementInArray {
public int findKthLargest(int[] nums, int k) {
Queue<Integer> pq = new PriorityQueue<Integer>();
for (int i : nums) {
pq.add(i);
if (pq.size() > k)
pq.poll();
}
return pq.peek();
}
/**
* Naive but actually fast initial solution.
*/
public int findKthLargest_var1(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}