public int[] maxSlidingWindow(int[] nums, int k) {
// 数组为空 直接返回空数组
if(nums.length == 0 || k == 0) {
return new int[0];
}
// 返回的结果
int res[] = new int[nums.length - k + 1];
// 左边界
int j = 0;
// k为右边界 超出nums.length为出口
while (k <= nums.length){
// 复制左右区间内的数组
int now[] = Arrays.copyOfRange(nums, j, k);
int temp = now[0];
// 循环找到最大值
for (int i = 1; i < now.length; i++){
temp = Math.max(temp, now[i]);
}
// 最大值加入结果集
res[j++] = temp;
k = k + 1;
}
return res;
}
Take a long time to see how the boss does it
public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length == 0 || k == 0) { return new int[0]; } // Monotonic queue And <Integer> = new LinkedList and <> (); int[] res = new int[nums.length - k + 1]; // No window is formed for(int i = 0; i < k; i++) { // Delete in a loop until the value in the queue is greater than the current value, or delete until the queue is empty while(!deque.isEmpty() && deque.peekLast() < nums[i]) { // When the queue is not empty, the current value is compared with the value of the tail of the queue, if it is greater, the value of the tail of the queue is deleted deque.removeLast (); } // After executing the above loop, the queue is either empty or the value is greater than the current value, and then the current value is added to the queue deque.addLast(nums[i]); } // The head of the line is the maximum value of the first window a [0] = deque.peekFirst (); // After forming the window for(int i = k; i < nums.length; i++) { // ik is already outside the range. If the first digit is equal to nums[ik], then the first value is no longer in the range and needs to be deleted. if(deque.peekFirst() == nums[i - k]){ deque.removeFirst (); } // Delete the value larger than the current value in the queue while(!deque.isEmpty() && deque.peekLast() < nums[i]) { deque.removeLast (); } // Add the current value to the queue deque.addLast(nums[i]); // Add the first value of the queue to the arr array res[i - k + 1] = deque.peekFirst(); } return res; }