Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-size-subarray-sum.py 1.53 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 13:24 +08:00 . update
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {integer} s
# @param {integer[]} nums
# @return {integer}
def minSubArrayLen(self, s, nums):
start = 0
sum = 0
min_size = float("inf")
for i in xrange(len(nums)):
sum += nums[i]
while sum >= s:
min_size = min(min_size, i - start + 1)
sum -= nums[start]
start += 1
return min_size if min_size != float("inf") else 0
# Time: O(nlogn)
# Space: O(n)
# Binary search solution.
class Solution2(object):
# @param {integer} s
# @param {integer[]} nums
# @return {integer}
def minSubArrayLen(self, s, nums):
min_size = float("inf")
sum_from_start = [n for n in nums]
for i in xrange(len(sum_from_start) - 1):
sum_from_start[i + 1] += sum_from_start[i]
for i in xrange(len(sum_from_start)):
end = self.binarySearch(lambda x, y: x <= y, sum_from_start, \
i, len(sum_from_start), \
sum_from_start[i] - nums[i] + s)
if end < len(sum_from_start):
min_size = min(min_size, end - i + 1)
return min_size if min_size != float("inf") else 0
def binarySearch(self, compare, A, start, end, target):
while start < end:
mid = start + (end - start) / 2
if compare(target, A[mid]):
end = mid
else:
start = mid + 1
return start
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助