[Algorithm Topic Breakthrough] Sliding Window-Subarray with Minimum Length (9)

Table of contents

1. Question analysis

2. Algorithm principle

3. Code writing

Write at the end:


1. Question analysis

Question link: 209. Minimum length subarray - Leetcode

 It should be noted that the question gives positive integers.

The question requirement is not difficult to understand, it is to find the shortest subarray.

2. Algorithm principle

If brute force is used, it is an O(N3) algorithm with high complexity.

We can do it with a sliding window. The sliding window is a vivid name, but it is actually a double-pointer algorithm.

When the two double pointers move in the same direction without going back, we call it a sliding window because it slides like a window.

So how do we use sliding windows to solve this problem?

1. Use two pointers as the left and right boundaries of the window

2. Enter the window

3. Determine how to exit the window

In terms of this question:

The two pointers left and right are first initialized to 0,

If the sum is less than the target value, let right++,

If the sum is greater than or equal to the target value, record the result, and then let left++. 

3. Code writing

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int n = nums.size(), sum = 0, len = INT_MAX;
        int left = 0, right = 0;
        while(right < n) {
            sum += nums[right];
            while(sum >= target) {
                len = min(len, right - left + 1);
                sum -= nums[left++];
            }
            right++;
        }
        return len == INT_MAX ? 0 : len;
    }
};

Write at the end:

That’s the content of this article, thank you for reading.

If you feel you have gained something, you can give the blogger a like .

If there are omissions or errors in the content of the article, please send a private message to the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131655722