每天(?)一道Leetcode(19) Minimum Size
2019-02-03 本文已影响0人
失业生1981
Array
209. Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
即 求子数组之和大于等于给定值的最小长度
要求实现O(n)和O(logn)两种算法
1.O(n)
- O(logn)
利用binary search
是一种在有序数组中查找某一特定元素的搜索算法。搜索过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜索过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
result = len(nums) + 1
for idx, n in enumerate(nums[1:], 1):
nums[idx] = nums[idx - 1] + n
left = 0
for right, n in enumerate(nums):
if n >= s:
left = self.find_left(left, right, nums, s, n)
result = min(result, right - left + 1)
return result if result <= len(nums) else 0
def find_left(self, left, right, nums, s, n):
while left < right:
mid = (left + right) // 2
if n - nums[mid] >= s:
left = mid + 1
else:
right = mid
return left