Untitled
unknown
plain_text
10 months ago
1.4 kB
3
Indexable
import java.util.*;
public class SlidingWindowMinimum {
public int[] minSlidingWindow(int[] nums, int k) {
int n = nums.length;
int[] result = new int[n - k + 1];
Deque<Integer> deque = new LinkedList<>();
int i = 0, j = 0, idx = 0;
// Process the first k elements
while (j < k) {
// Remove larger elements as they are not useful
while (!deque.isEmpty() && nums[deque.peekLast()] >= nums[j]) {
deque.pollLast();
}
deque.addLast(j);
j++;
}
// Store the minimum for the first window
result[idx++] = nums[deque.peekFirst()];
// Process the rest of the elements
while (j < n) {
// Remove larger elements as they are not useful
while (!deque.isEmpty() && nums[deque.peekLast()] >= nums[j]) {
deque.pollLast();
}
deque.addLast(j);
i++;
// Remove elements not in the current window
if (!deque.isEmpty() && deque.peekFirst() < i) {
deque.pollFirst();
}
// Store the minimum for the current window
result[idx++] = nums[deque.peekFirst()];
j++;
}
return result;
}
}
Editor is loading...
Leave a Comment