Learn More →
Leetcode
Medium
Average Rating:
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr]
of which the sum is greater than or equal to target. If there is no such subarray, return 0
instead.
Example 1
Example 2
Constraints:
Follow up: If you have figured out the O(n)
solution, try coding another solution of which the time complexity is O(n log(n))
.
English Version
For this question, we are expected to find the minimal length of sub-array, which has to be contiguous, and can be larger than the target
instead of equal to the target
only.
For this question, brute-force is not a wise choice. We should try sliding window which can also be called two-pointers method.
Algorithm:
left
and right
left pointer
= 0
, right
= left +1
right
to the tail of the arraysum
of array[left,right]
>= targetleft +1
Chinese Version
滑动窗口的核心是明确以下几点:
首先, 满足形成窗口的条件是,窗口内value
的和 >= target
. 此时窗口内就是一个符合题目要求的sub-array.
起始位置left移动的条件:当前sum>=target
结束位置移动的条件:right
其实就是一个遍历array的指针
整个算法结束的标志:left
遍历完整个array
主要逻辑:
如果当前位置下滑动窗口里的值>target,那么缩小一下窗口,再往右划
Python
Python: same as above
904 76