LeetCode (力锋) 209 questions: The shortest sub-array whose sum is greater than or equal to the target----sliding window solution with detailed notes

题目描述
Given an array of n positive integers and a positive integer target.

Find the smallest continuous subarray in the array that satisfies its sum ≥ target [ numsi nums_in u m si, n u m s i + 1 nums_{i+1} n u m si+1, …, n u m s r − 1 nums_{r-1} n u m sr1, n u m s r nums_r n u m sr] , and returns its length. Returns 0 if no matching subarray exists.

示例

输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
输入:target = 4, nums = [1,4,4]
输出:1
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0

思路分析
Question Meaning Given an unnecessary positive integer array with a capacity of n and a positive integer target, we need to find the shortest sub-array whose sum is greater than or equal to target. Because it is unordered , and what we are looking for is a continuous sub-array , then it is more natural to think of the sliding window method. Set the starting point left and the ending point right of the window , and gradually slide from the left end of the array to the right end, during which the window size is adjusted according to the sum of the sub-arrays covered by the window. Assuming that the sum of the subarrays in the window is greater than or equal to the target at this time, the elements at the starting point of the window are removed until the sum of elements in the window is less than the target, and then the end of the window continues to be expanded, and so on, until the end of the window moves to the rightmost end of the array.

It may be more abstract to say this, and you can probably understand it by looking at the code.

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        if sum(nums) < target:
            return 0
        ans = len(nums) #最终返回的结果
        res = 0 #滑动窗口覆盖子数组的和
        #题意要求找到和>=target的最短连续子数组
        #首先想到使用滑动窗口的方法解决问题
        l, r = 0, 0 #定义窗口的起点和终点
        while r < len(nums):
        	#窗口终点向右滑动
            res += nums[r]
            #如果窗口覆盖子数组的值>=target, 调整窗口起点的位置 
            while res >= target:
                ans = min(ans, r - l + 1)
                res -= nums[l]
                l += 1
            #窗口起点调整好之后,继续向前移动
            r += 1
        return ans

程序运行结果
insert image description here
It can be seen that the efficiency of the code is still very high.

总结
After doing some array questions, I found that most of the array questions can be solved by binary search, double pointer, dynamic programming and other methods. You can choose a specific method according to the specific question. You must learn to abstract the mathematical model from the meaning of the question, and then do it decision making.

おすすめ

転載: blog.csdn.net/Just_do_myself/article/details/119784403