Skip to content

Commit 65fbd29

Browse files
authored
Create K Smallest Elements
1 parent 0e27454 commit 65fbd29

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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 smallest numbers from given array.
3+
You need to save them in an array and return it.
4+
Time complexity should be O(n * logk) and space complexity should not be more than O(k).
5+
Note: Order of elements in the output is not important.
6+
7+
Input Format :
8+
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
9+
The following line contains N space separated integers, that denote the value of the elements of the array.
10+
The following line contains an integer, that denotes the value of k.
11+
12+
Output Format :
13+
The first and only line of output print k smallest elements. The elements in the output are separated by a single space.
14+
15+
Constraints:
16+
Time Limit: 1 sec
17+
18+
Sample Input 1 :
19+
13
20+
2 12 9 16 10 5 3 20 25 11 1 8 6
21+
4
22+
Sample Output 1 :
23+
1 2 3 5
24+
*/
25+
26+
//import java.util.ArrayList;
27+
import java.util.*;
28+
public class Solution {
29+
30+
public static ArrayList<Integer> kSmallest(int n, int[] input, int k) {
31+
// Write your code here
32+
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
33+
for(int i=0;i<k;i++)
34+
{
35+
pq.add(input[i]);
36+
}
37+
38+
for(int i=k;i<input.length;i++)
39+
{
40+
int maxVal=pq.peek();
41+
if(maxVal>input[i])
42+
maxVal=input[i];
43+
if(maxVal!=pq.peek())
44+
{
45+
pq.poll();
46+
pq.add(maxVal);
47+
}
48+
}
49+
ArrayList<Integer> arr = new ArrayList<Integer>();
50+
while(!pq.isEmpty())
51+
arr.add(pq.poll());
52+
return arr;
53+
54+
}
55+
}

0 commit comments

Comments
 (0)