Algorithm training|sliding window

Mode 1: Sliding window

Mode description: Enter an array or string. The result of the solution is a sub-array or sub-string with a certain characteristic. In this case, the sliding window method can be used to solve the problem.

Among them, the sliding window is an array with a variable size. The most important thing is to determine how the start pointer and end pointer of this array move.

Insert picture description here
From the above question, if the condition is met, the left pointer is killed, that is, the left pointer moves one place to the right, if the condition is not met, the right pointer moves one place to the right.

JAVA implementation:

class Solution {
    
    
    public int minSubArrayLen(int target, int[] nums) {
    
    
        //原数组的长度
        int length = nums.length;
        //返回的结果
        int ans = Integer.MAX_VALUE;
        //左指针
        int left = 0,right = 0;
        //窗口元素的和
        int sum = 0;
        //判断边界条件
        if(length == 0){
    
    
            return 0;
        }
        while(right < length){
    
    
            //右指针遍历数组
            sum += nums[right];
            while(sum >= target){
    
    
                //更新窗口
                sum -= nums[left];
                //寻找最小子数组
                ans = Math.min(ans,right-left+1);
                //左指针++
                left++;
            }
            //右指针++
            right++;
        }
        return ans == Integer.MAX_VALUE?0:ans;
    }
}

Insert picture description here
C++ implementation:

class Solution {
    
    
public:
    int minSubArrayLen(int s, vector<int>& nums) {
    
    
        int result = INT32_MAX;
        int sum = 0; // 滑动窗口数值之和
        int i = 0; // 滑动窗口起始位置
        int subLength = 0; // 滑动窗口的长度
        for (int j = 0; j < nums.size(); j++) {
    
    
            sum += nums[j];
            // 注意这里使用while,每次更新 i(起始位置),并不断比较子序列是否符合条件
            while (sum >= s) {
    
    
                subLength = (j - i + 1); // 取子序列的长度
                result = result < subLength ? result : subLength;
                sum -= nums[i++]; // 这里体现出滑动窗口的精髓之处,不断变更i(子序列的起始位置)
            }
        }
        // 如果result没有被赋值的话,就返回0,说明没有符合条件的子序列
        return result == INT32_MAX ? 0 : result;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45394002/article/details/115314739