generated from IA-Labs-Official/Core-Java-Assignment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution3.java
44 lines (29 loc) · 939 Bytes
/
Solution3.java
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
38
39
40
41
42
43
44
package com.assignment4;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
class Solution3
{
public static int findKthLargest(List<Integer> ints, int k)
{
if (ints == null || ints.size() < k) {
System.exit(-1);
}
PriorityQueue<Integer> pq = new PriorityQueue<>(ints.subList(0, k));
for (int i = k; i < ints.size(); i++)
{
if (ints.get(i) > pq.peek())
{
pq.poll();
pq.add(ints.get(i));
}
}
return pq.peek();
}
public static void main(String[] args)
{
List<Integer> ints = Arrays.asList(7, 4, 6, 3, 9, 1);
int k = 3;
System.out.println("k'th largest array element is " + findKthLargest(ints, k));
}
}