-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
36 lines (31 loc) · 923 Bytes
/
Copy pathsolution.cpp
File metadata and controls
36 lines (31 loc) · 923 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void nearlySorted(vector<int> &arr, int k)
{
int n = arr.size();
if (n <= 1 || k <= 0)
return; // already sorted or no displacement
// min-heap
priority_queue<int, vector<int>, greater<int>> pq;
// push first k+1 elements (or all if smaller)
for (int i = 0; i < n && i <= k; ++i)
pq.push(arr[i]);
int index = 0; // position to place smallest element
// for the rest of the elements, push next and pop smallest to place
for (int i = k + 1; i < n; ++i)
{
arr[index++] = pq.top();
pq.pop();
pq.push(arr[i]);
}
// empty remaining heap
while (!pq.empty())
{
arr[index++] = pq.top();
pq.pop();
}
}
};