-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKLargestElements.java
More file actions
52 lines (47 loc) · 1.41 KB
/
KLargestElements.java
File metadata and controls
52 lines (47 loc) · 1.41 KB
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
45
46
47
48
49
50
51
52
// K Largest Elements
// Send Feedback
// You are given with an integer k and an array of integers that contain numbers
// in random order. Write a program to find k largest numbers from given array.
// You need to save them in an array and return it.
// Time complexity should be O(nlogk) and space complexity should be not more
// than O(k).
// Order of elements in the output is not important.
// Input Format :
// Line 1 : Size of array (n)
// Line 2 : Array elements (separated by space)
// Line 3 : Integer k
// Output Format :
// k largest elements
// Sample Input :
// 13
// 2 12 9 16 10 5 3 20 25 11 1 8 6
// 4
// Sample Output :
// 12
// 16
// 20
// 25
import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
public class Solution {
public static ArrayList<Integer> kLargest(int input[], int k) {
/*
* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i : input) {
pq.add(i);
}
ArrayList<Integer> arr = new ArrayList<>();
while (k > 0) {
arr.add(pq.poll());
k--;
}
return arr;
}
}