-
Notifications
You must be signed in to change notification settings - Fork 0
/
nearly-sorted.cpp
60 lines (47 loc) · 1.08 KB
/
nearly-sorted.cpp
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
53
54
55
56
57
58
59
60
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to return the sorted array.
vector <int> nearlySorted(int arr[], int n, int k){
// Your code here
priority_queue<int, vector<int> , greater<int> > pq;
for(int i = 0; i <= k; i++){
pq.push(arr[i]);
}
vector<int> ans;
ans.push_back(pq.top());
pq.pop();
for(int i = 1; i < n; i++){
if(i + k < n) pq.push(arr[i + k]);
ans.push_back(pq.top());
pq.pop();
}
return ans;
}
};
// { Driver Code Starts.
int main()
{
int T;
cin>> T;
while (T--)
{
int num, K;
cin>>num>>K;
int arr[num];
for(int i = 0; i<num; ++i){
cin>>arr[i];
}
Solution ob;
vector <int> res = ob.nearlySorted(arr, num, K);
for (int i = 0; i < res.size (); i++)
cout << res[i] << " ";
cout<<endl;
}
return 0;
}
// } Driver Code Ends