You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
3
+
You need to save them in an array and return it.
4
+
Time complexity should be O(nlogk) and space complexity should be not more than O(k).
5
+
Order of elements in the output is not important.
6
+
7
+
Input Format :
8
+
Line 1 : Size of array (n)
9
+
Line 2 : Array elements (separated by space)
10
+
Line 3 : Integer k
11
+
12
+
Output Format :
13
+
k largest elements
14
+
15
+
Sample Input :
16
+
13
17
+
2 12 9 16 10 5 3 20 25 11 1 8 6
18
+
4
19
+
Sample Output :
20
+
12
21
+
16
22
+
20
23
+
25
24
+
*/
25
+
26
+
import java.util.ArrayList;
27
+
import java.util.PriorityQueue;
28
+
public class Solution {
29
+
30
+
public static ArrayList<Integer> kLargest(int input[], int k) {
31
+
/* Your class should be named Solution
32
+
* Don't write main().
33
+
* Don't read input, it is passed as function argument.
34
+
* Return output and don't print it.
35
+
* Taking input and printing output is handled automatically.
36
+
*/
37
+
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
38
+
for(int i=0;i<k;i++)
39
+
{
40
+
pq.add(input[i]);
41
+
}
42
+
43
+
for(int i=k;i<input.length;i++)
44
+
{
45
+
int minVal=pq.peek();
46
+
if(minVal<input[i])
47
+
minVal=input[i];
48
+
if(minVal!=pq.peek())
49
+
{
50
+
pq.poll();
51
+
pq.add(minVal);
52
+
}
53
+
}
54
+
ArrayList<Integer> arr = new ArrayList<Integer>();
0 commit comments