Sliding Window Maximum

本文详细介绍了如何使用双向队列解决滑动窗口最大值问题,包括两种实现方式及其代码示例。重点突出算法的核心思想和关键步骤。
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7].

Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

滑动窗口的题目,我们可以借助双向队列deque来解决。一边维护窗口的大小,一边将每个窗口的中的最大元素放在队列的头部,这样每次取队列的第一个元素就可以了。代码如下:

public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0) return new int[0];
int[] result = new int[nums.length - k + 1];
Deque<Integer> deque = new LinkedList<Integer>();
int index = 0;
for(int i = 0; i < nums.length; i++) {
//查看之前的最大元素是否在窗口中,如果不在就删除
if(!deque.isEmpty() && (deque.getFirst() == (i - k)))
deque.removeFirst();

//添加新的元素到队尾
while(!deque.isEmpty() && nums[deque.getLast()] <= nums[i])
deque.removeLast();
deque.addLast(i);

//将最大元素加入到结果中
if(i >= k - 1) result[index ++] = nums[deque.getFirst()];
}
return result;
}
}


如果不用队列也可以,思路是一样的,维护一个窗口,当窗口移动之后,检查之前窗口的最大元素是否在移动后的窗口中,如果在只需要比较最大元素与新近的元素就可以;如果不存在就在新窗口中找最大元素。代码如下:

public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0) return new int[0];
int[] result = new int[nums.length - k + 1];
int maxIndex = 0;
int max = Integer.MIN_VALUE;
int index = 0;
for(int i = 0; i < result.length; i++) {
if(i == 0 || maxIndex == i - 1) {
max = Integer.MIN_VALUE;
for(int j = i; j < i + k; j++)
if(nums[j] > max) {
max = nums[j];
maxIndex = j;
}
}else {
if(nums[i + k - 1] > max) {
max = nums[i + k - 1];
maxIndex = i + k - 1;
}
}
result[index ++] = max;
}
return result;
}
}
### Sliding Window Algorithm for Array Processing and Buffer Manipulation The sliding window algorithm is a powerful technique used in array processing and buffer manipulation to efficiently solve problems involving subarrays or subbuffers of a specific size. It is particularly useful when dealing with large data sets, as it can reduce time complexity significantly compared to brute-force approaches. #### Basic Concept The idea behind the sliding window algorithm is to maintain a window of fixed size `k` that slides over the data structure (typically an array or buffer). As the window moves one position at a time, computations are performed on the elements within the window. This allows for efficient processing of each window without recalculating values from scratch every time. For example, consider an array `[1, 3, -1, -3, 5, 3, 6, 7]` with a window size of `3`. The windows would be `[1, 3, -1]`, `[3, -1, -3]`, `[-1, -3, 5]`, and so on. The minimum and maximum values for each window can be determined efficiently using this approach [^4]. #### Applications 1. **Finding Maximum or Minimum Values in Subarrays** A common application is to determine the maximum or minimum value in each sliding window of size `k`. This is often used in data stream analysis and real-time systems where quick access to statistical measures is required. 2. **Sum or Average of Subarrays** The algorithm can be used to calculate the sum or average of all subarrays of size `k`. This is useful in signal processing, image processing, and financial data analysis. 3. **Substring Search and Pattern Matching** In string algorithms, the sliding window technique is used for substring search and pattern matching problems, such as finding the smallest window in a string containing all characters of another string. 4. **Data Stream Analysis** Sliding window algorithms are used in data stream processing to maintain aggregates and statistics over a fixed window of recent data. This is particularly useful in network monitoring and real-time analytics. #### Implementation Example A typical implementation for finding the maximum value in each sliding window of size `k` can be done using a deque (double-ended queue) to maintain indices of potential maximum values efficiently. ```python from collections import deque def sliding_window_max(nums, k): if not nums: return [] result = [] dq = deque() for i in range(len(nums)): # Remove indices out of the current window while dq and dq[0] < i - k + 1: dq.popleft() # Remove indices of all elements smaller than the current element while dq and nums[dq[-1]] < nums[i]: dq.pop() dq.append(i) # Append the maximum value for the current window if i >= k - 1: result.append(nums[dq[0]]) return result # Example usage nums = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 print(sliding_window_max(nums, k)) # Output: [3, 3, 5, 5, 6, 7] ``` #### Time and Space Complexity - **Time Complexity**: The algorithm runs in O(n) time, where `n` is the size of the input array. Each element is added and removed from the deque at most once. - **Space Complexity**: The space complexity is O(k) for storing the deque, which holds at most `k` elements corresponding to the current window. #### Advantages - **Efficiency**: The sliding window technique significantly reduces redundant computations by reusing results from previous windows. - **Scalability**: It is well-suited for large data sets and real-time applications due to its linear time complexity. #### Limitations - **Fixed Window Size**: Most implementations assume a fixed window size, which may not be suitable for all applications. - **Complexity in Implementation**: Maintaining the window and managing data structures like deques can add complexity to the code. #### Variations 1. **Variable-Size Sliding Window**: In some problems, the window size is not fixed, and the goal is to find the smallest or largest subarray satisfying certain conditions. Techniques like two pointers are often used in such cases. 2. **Circular Sliding Window**: In some applications, the window wraps around the end of the array, requiring special handling. #### Conclusion The sliding window algorithm is a versatile and efficient method for processing arrays and buffers, particularly when dealing with subarrays of fixed size. Its ability to reduce time complexity makes it a preferred choice for large-scale data processing tasks. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值