239. 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.

Follow up:
Could you solve it in linear time?

Hint:

  1. How about using a data structure such as deque (double-ended queue)?
  2. The queue size need not be the same as the window’s size.
  3. Remove redundant elements and the queue should store only elements that need to be considered.
题意:给定一个数组,然后以一个k大小的窗口在数组上滑动,返回每次窗口对应中的最大值。

思路:原本以为前k个元素建立一个堆,然后后续的元素一个一个的替换进堆里,然后每次返回出最大的元素,问题在于无法找到堆中要加入的那个元素的对应位置,且时间复杂度不是线性。按照提示的思路进行,先建立一个双端队列,然后每加入一个元素都把队列中这个元素之前的比这个元素小的值给删除,因为他们不可能是最大值了,这样维持了双端队列中从左至右元素依次递减的特性(最大的就在队列第一个位置),每次新加入元素前,检测队列里第一个元素之是否已经移出窗口,然后再进行操作。队列里存放的是数组里值对应的下标,这样方便计算队列首元素是否已经滑出窗口。

class Solution {
public:
	vector<int> maxSlidingWindow(vector<int>& nums, int k) {
		int len = nums.size();
		if (len == 0)
			return vector<int>();
		vector<int> res(len - k+1);
		deque<int> mydeque(1, 0);//队列里存储的是数组的下标
		for (int i = 1; i < k; i++){
			for (int j = mydeque.size() - 1; j >= 0; j--){
				if (nums[mydeque[j]] < nums[i]){
					mydeque.pop_back();
				}
			}
			mydeque.push_back(i);
		}
		res[0] = nums[mydeque[0]];
		for (int i = k; i < len; i++){
			if (mydeque[0] < i-k+1){
				mydeque.pop_front();
			}
			for (int j = mydeque.size() - 1; j >= 0; j--){
				if (nums[mydeque[j]] < nums[i]){
					mydeque.pop_back();
				}
			}
			mydeque.push_back(i);
			res[i - k + 1] = nums[mydeque[0]];
		}
		return res;
	}
};






### 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、付费专栏及课程。

余额充值