之前用暴力求解超时了,改为双指针滑窗就好了
class Solution:
def minSubArrayLen(self, target, nums):
n = len(nums)
ans = n + 1
left = 0 # 左指针
temp = 0 # num[left:i+1]的累加和
for i in range(n): # i为右指针
temp += nums[i]
while temp >= target:
ans = min(ans, i - left + 1)
temp -= nums[left]
left += 1
if ans == n + 1:
return 0
else:
return ans
target = 7
nums = [2,3,1,2,4,3]
print(Solution().minSubArrayLen(target, nums))
博客提到之前使用暴力求解出现超时问题,之后采用双指针滑窗方法解决了该问题,体现了算法优化在编程中的重要性,涉及Python和数据结构相关知识。
299

被折叠的 条评论
为什么被折叠?



