Initial recognition algorithm · Sliding window (1)

Table of contents

 Preface:

The subarray with the smallest length

Question Analysis

Algorithm Principle

Algorithm Writing

Minimum string length without repetitions

Question Analysis

Algorithm Principle

Algorithm Writing


 Preface:

At the beginning of this article, we introduce the sliding window algorithm type. The sliding window is actually a double pointer in nature. However, the double pointers introduced in the previous article move towards each other:

The sliding window moves in the same direction:

This article introduces the basic use of sliding windows through two topics. The topics introduced are:

209. Minimum Subarray - LeetCode

3. The longest substring without repeated characters - LeetCode

It is introduced in three steps. The first step is question analysis, the second step is algorithm principle, and the third step is algorithm writing. Similarly, we will check whether there is a brute force solution in the question analysis part. So without further ado, let’s move on to the first question.


The subarray with the smallest length

Question Analysis

The question requires you to find a continuous interval such that the sum of the values ​​in the interval is greater than or equal to the target. If there is such an interval, the return value should be the minimum length of these intervals. If there is no such subarray, the return value should be 0.

Then there are two examples. So can we use brute force to solve this problem? Of course we can.

We only need to find all the intervals that meet the condition and determine their lengths. However, the time complexity is definitely O(N^2), and we will time out on this question, so interested students can try it on their own.

So why can a sliding window be used in this question?

Because what is required is a continuous space , as a rule of thumb, when we encounter a question that requires a continuous space, we might as well move towards the sliding window.

Now let’s move on to the algorithm principle part.

Algorithm Principle

The essence of the sliding window is that the two pointers move in the same direction. We use the movement of the two pointers to determine whether the sum of the intervals is satisfied. If so, we compare the lengths.

What if we use a sliding window?
The starting points of the two pointers should be the same at the beginning. If the positions of the two pointers are not the same, we will need to add an extra loop to specifically calculate the sum of this interval, so now:

int left = 0, right = 0;

This is for sure. For the sliding window, we can remember two nouns, one is the entry window and the other is the exit window. When to enter the window and what is the exit window are what our topic is concerned with.

Entering the window means that the sum of the intervals is less than the target, so more numbers are needed to participate. This is why we don’t need to sort. The question itself requires a positive integer, so we only need to ensure that the more numbers there are, the better.

The exit window represents that the sum of the intervals > target, and the exit window determines the minimum length that exists in it.

This is the basic principle. By moving in and out, you can solve the problem successfully.

Algorithm Writing

class Solution 
{
public:
    int minSubArrayLen(int target, vector<int>& nums) 
    {
        int ans = INT_MAX, left = 0, right = 0 ,sum = 0;
        for(;right < nums.size();right++)
        {
            sum += nums[right];
            while(sum >= target) 
            {
                ans = min(ans,right - left + 1);//如果ans为0 那么这一步永远都是0
                sum -= nums[left++];
            }
        }
        return ans == INT_MAX ? 0 : ans;
    }
};

But there is a disgusting point in this question. If the initial length is not defined as a very large number, the minimum number cannot be obtained through min when judging and comparing. Therefore, we should define ans as INT_MAX, as long as it is a very large number.

At this point, the question has been analyzed.


Minimum string length without repetitions

Question Analysis

The question is very short. The passing condition is to return the length of the longest string without repeated characters. For characters, the requirements given in the question are:

So in order to determine whether there is duplication, we need a way to determine whether there is some kind of mapping. We might as well use hash mapping here and use arrays to imitate hash tables. Then first of all, we might as well determine whether there is a brute force solution to the problem.

It definitely exists. We use two for loops. The second loop finds the last element and checks whether the mapped value is greater than 1. If it is greater than 1, we can return it directly. The time complexity is definitely O(N^2), which is acceptable.

However, given that the essence of this problem is an interval, we might as well use a sliding window to solve it.

Algorithm Principle

The sliding window of the previous question is the subarray with the smallest length, and the judgment condition is greater than or equal to >= target. The judgment condition of this question is whether the hash mapping is greater than 1. Therefore, we can draw a conclusion that there are three steps to using sliding windows. The first is entering the window, the second is judgment, and the third is exiting the window .

The following questions all use this step in a very rigid manner.

Then our judgment method is also to use hash mapping. If the mapping is greater than 1, it will be output, and the corresponding ans will be recorded after it is output. Or if the mapping meets the conditions, the corresponding ans can also be recorded.

Finally, just return to ans.

Algorithm Writing

class Solution 
{
public:
    int lengthOfLongestSubstring(string s) 
    {
        int hash[256] = { 0 }, ans = 0;
        for(int left = 0, right = 0;right < s.size();right++)
        {
            hash[s[right]]++;
            while(hash[s[right]] > 1)
            {
                hash[s[left++]]--;
            }
            ans = max(ans,right - left + 1);
        }
        return ans;
    }
};

The beginning of the sliding window ends~


Thanks for reading!

Guess you like

Origin blog.csdn.net/2301_79697943/article/details/142713599