Code : K smallest Elements
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.
The following line contains N space separated integers, that denote the value of the elements of the array.
The following line contains an integer, that denotes the value of k.
The first and only line of output print k smallest elements. The elements in the output are separated by a single space.
Time Limit: 1 sec
13
2 12 9 16 10 5 3 20 25 11 1 8 6
4
1 2 3 5
#include<bits/stdc++.h>vector<int> kSmallest(int arr[], int n, int k) { // Write your code here priority_queue<int, vector<int>>minh; vector<int>v; for(int i=0;i<n;i++){ minh.push(arr[i]); if(minh.size()>k){ minh.pop(); } }
for(int i=0;i<k;i++){ v.push_back(minh.top()); minh.pop(); }
return v;
}
Comments
Post a Comment