239. Sliding Window Maximum

本文探讨了在给定数组中寻找滑动窗口最大值的两种高效算法:使用优先级队列和双数组方法。通过实例说明了算法的实现过程,并分析了其时间和空间复杂度。
Description

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. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:
Could you solve it in linear time?

Problem URL


Solution

给一数组,和一个滑动窗口的大小,找到每一次滑动窗口后窗口内数的最大值。

A simple idea is to maintain a prioriyt queue which has the size of k. Feed to prioriyt queue to k first, then every time the window moves, we remove first number out or pq and add new number. Then the peek value in pq is max value of this window, store it to res array.

Code
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums.length == 0 || k <= 0){
            return new int[0];
        }
        int len = nums.length;
        int[] res = new int[len - k + 1];
        Queue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
            @Override
            public int compare(Integer n1, Integer n2){
                return Integer.compare(n2, n1);
            }
        });
        for(int i = 0; i < k; i++){
            pq.add(nums[i]);
        }
        res[0] = pq.peek();
        for (int i = k; i < len; i++){
            pq.remove(nums[i - k]);
            pq.add(nums[i]);
            res[i - k + 1] = pq.peek();
        }
        return res;
    }
}

Time Complexity: O(nk)
Space Complexity: O(k)


Review

Another linear time approach is to divide the nums array into subsequence size of k. Maintain two arrays which denote the max value from left to right and from right to left in each subsequence. The max value of a window start at I is Math.max(leftMax[i + k -1], rightMax[i]

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int len = nums.length;
        if (len == 0 || k <= 0){
            return new int[0];
        }
        int[] leftMax = new int[len];
        int[] rightMax = new int[len];
        int[] res = new int[len - k + 1];
        leftMax[0] = nums[0];
        rightMax[len - 1] = nums[len - 1];
        for (int i = 1, j = 0; i < len; i++){
            leftMax[i] = i % k == 0 ? nums[i] : Math.max(leftMax[i - 1], nums[i]);
            j = len - i - 1;
            rightMax[j] = j % k == 0 ? nums[j] : Math.max(rightMax[j + 1], nums[j]);
        }
        
        for (int i = 0, j = 0; i + k <= len; i++){
            res[j++] = Math.max(rightMax[i], leftMax[i + k - 1]);
        }
        return res;
    }
}

Time Complexity: O(n)
Space Complexity: O(n)
reference

### 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. ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值