forked from ByteByteGoHq/coding-interview-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortAKSortedArray.java
More file actions
25 lines (24 loc) · 881 Bytes
/
SortAKSortedArray.java
File metadata and controls
25 lines (24 loc) · 881 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
import java.util.PriorityQueue;
public class SortAKSortedArray {
public int[] sortAKSortedArray(int[] nums, int k) {
// Populate a min-heap with the first k + 1 values in 'nums'.
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int i = 0; i < k + 1; i++) {
minHeap.offer(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 < nums.length; i++) {
nums[insertIndex] = minHeap.poll();
insertIndex++;
minHeap.offer(nums[i]);
}
// Pop the remaining elements from the heap to finish sorting the array.
while (!minHeap.isEmpty()) {
nums[insertIndex] = minHeap.poll();
insertIndex++;
}
return nums;
}
}