forked from ByteByteGoHq/coding-interview-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_a_k_sorted_array.cpp
More file actions
27 lines (26 loc) · 857 Bytes
/
sort_a_k_sorted_array.cpp
File metadata and controls
27 lines (26 loc) · 857 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
#include <vector>
#include <queue>
std::vector<int> sortAKSortedArray(std::vector<int>& nums, int k) {
// Populate a min-heap with the first k + 1 values in 'nums'.
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
int n = nums.size();
for (int i = 0; i <= k && i < n; i++) {
minHeap.push(nums[i]);
}
// Replace elements in the array with the minimum from the heap at each
// iteration.
int insertIndex = 0;
for (int i = k + 1; i < n; i++) {
nums[insertIndex] = minHeap.top();
minHeap.pop();
insertIndex++;
minHeap.push(nums[i]);
}
// Pop the remaining elements from the heap to finish sorting the array.
while (!minHeap.empty()) {
nums[insertIndex] = minHeap.top();
minHeap.pop();
insertIndex++;
}
return nums;
}