Skip to content

Commit 4ab523a

Browse files
committed
和大于S的最小子数组
1 parent d05465e commit 4ab523a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

minimum_size_subarray_sum.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param nums: a list of integers
5+
# @param s: an integer
6+
# @return: an integer representing the minimum size of subarray
7+
def minimumSize(self, nums, s):
8+
# write your code here
9+
# 两个指针一前一后,先找到大于s,在移动后面使得小于s,再移动前面。。。
10+
ret = 2147483647
11+
if nums:
12+
slow, fast = 0, 0
13+
_sum = 0
14+
while fast < len(nums):
15+
while (fast < len(nums)) and (_sum < s):
16+
_sum += nums[fast]
17+
fast += 1
18+
while _sum >= s:
19+
ret = min(fast - slow, ret)
20+
_sum -= nums[slow]
21+
slow += 1
22+
return -1 if ret == 2147483647 else ret
23+
24+
# TODO: nLog(n)复杂度的算法

0 commit comments

Comments
 (0)