209. Minimum Size Subarray Sum
题目来源:https://leetcode.com/problems/minimum-size-subarray-sum/
自我感觉难度/真实难度: 写题时间时长:
题意:
分析:
自己的代码:
class Solution(object): def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ l,r=0,-1 sumall=0 length=len(nums) res=length+1 while l<length: if sumall<s and r+1<length: r+=1 sumall+=nums[r] else: sumall-=nums[l] l+=1 if sumall>=s: res=min(res,r-l+1) if res==length+1: return 0 else: return res
从玩转算法面试看到的一个解法,主要是使用滑动窗口的技术
代码效率/结果:
Runtime: 60 ms, faster than 51.18% of Python online submissions for Minimum Size Subarray Sum.
Memory Usage: 14.1 MB, less than 5.80% of Python online submissions forMinimum Size Subarray Sum.
优秀代码:
class Solution(object): def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ ans = 100000 left = 0 sum_ = 0 for i,val in enumerate(nums): sum_ += val while(sum_ >= s): ans = min(ans,i+1-left) sum_ -= nums[left] left += 1 return ans if ans != 100000 else 0
主要是使用了enumerate,速度快得很
代码效率/结果:
24 ms submission
自己优化后的代码:
反思改进策略:
1.注意滑动窗口的结束条件
2.注意里面滑动窗口里面,变化是有先后顺序的
3.其中,边界条件的判断,不能越界。可以取等于最小值的情况