1 class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         int idx1=0,idx2=0;
 4         int currSum=0;
 5         int ret=Integer.MAX_VALUE;
 6         while(idx2<nums.length)
 7         {
 8             currSum+=nums[idx2];
 9             idx2++;
10             if(currSum>=s)
11             {
12                 while(currSum>=s)
13                 {
14                     currSum-=nums[idx1];
15                     idx1++;
16                 }
17                 ret=Math.min(ret,idx2-idx1+1);
18             }
19         }
20         return ret==Integer.MAX_VALUE?0:ret;
21     }
22 }

参考:https://leetcode.com/problems/minimum-size-subarray-sum/discuss/557651/Java-Solution-O(n)-time-O(1)-space-(Easy-to-Understand)

算法思路:滑动窗口,双指针

使用两个指针记录窗口的左右边界,计算窗口内元素之和currSum,

如果currSum < s,则继续扩展窗口的长度,右边界增加。

如果currSum >= s,则尝试缩小窗口的长度,左边界增加。并在条件不满的时候,记录此时的临界状态下的窗口长度。

 

下面给出一个python的实现,代码思路与上面的java是一样的:

 1 class Solution:
 2     def minSubArrayLen(self, s: int, nums: 'List[int]') -> int:
 3         n = len(nums)
 4         left,right =0,0
 5         minlen = n + 1
 6         cursum = 0
 7         while right < n:
 8             cursum += nums[right]
 9             right += 1
10             if cursum >= s:
11                 while cursum >= s:
12                     cursum -= nums[left]
13                     left += 1
14                 minlen = min(minlen,right-left+1)
15         return minlen if minlen <= n else 0

 

posted on 2020-04-03 09:31  Sempron2800+  阅读(178)  评论(0编辑  收藏  举报