Skip to content

Commit 0e27454

Browse files
authored
Create K Largest Elements
1 parent ab78988 commit 0e27454

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
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>();
55+
while(!pq.isEmpty())
56+
arr.add(pq.poll());
57+
return arr;
58+
59+
}
60+
}

0 commit comments

Comments
 (0)