#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
題目裡面沒要求連續子數組...但是解題時得按照連續子數組來解,郁悶
'''
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
非連續子數組,最少個數
"""
length = len(nums)
if length == :
return
nums.sort()
index = length -
while index >= and s > :
s = s - nums[index]
index -=
if s > :
return
return length - -index
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
leetcode答案,連續子數組最少個數
"""
length = len(nums)
if length == :
return
sum = nums[]
start,end = ,
min_len = length
tmp_len =
while end < length and start < end:
if sum < s:
sum += nums[end]
end +=
tmp_len +=
elif sum >= s:
if tmp_len < min_len:
min_len = tmp_len
sum -= nums[start]
start +=
tmp_len -=
if min_len == length and sum < s:#整個數組的和沒有s大
return
while sum > s and (sum - nums[start]) >= s and start < length:
sum -= nums[start]
tmp_len -=
if tmp_len < min_len:
min_len = tmp_len
start +=
return min_len