# python3 classSolution: """ @param nums: an array of integers @param s: An integer @return: an integer representing the minimum size of subarray """ defminimumSize(self, nums, s): # write your code here min_length = float("inf") for start inrange(len(nums)): for end inrange(start,len(nums)): sum_of_subarray = 0 for i inrange(start,end + 1): sum_of_subarray += nums[i] if sum_of_subarray >= s: min_length = min(min_length,end-start+1) if min_length == float("inf"): return -1 return min_length
# Time Limit Exceeded
前缀和优化
首先使用 O(n) 的时间获得前缀和数组 然后O(n ^ 2)枚举起点终点,同时借助前缀和计算子数组和 子数组和 >= s :更新子数组的长度
# python3 classSolution: """ @param nums: an array of integers @param s: An integer @return: an integer representing the minimum size of subarray """ defminimumSize(self, nums, s): # write your code here # n = len(nums) prefix_sum = self.get_prefix_sum(nums) min_length = float("inf") for start inrange(len(nums)): for end inrange(start,len(nums)): if prefix_sum[end + 1] - prefix_sum[start] >= s: min_length = min(min_length,end - start + 1)
if min_length == float("inf"): return -1 return min_length
defget_prefix_sum(self,nums): prefix_sum = [0] for i inrange(1,len(nums) + 1): prefix_sum.append(prefix_sum[i - 1] + nums[i - 1]) return prefix_sum
二分
对于每个下标 i ,都让他作为子数组左边界 使用二分法找出子数组最靠左的右边界 使用前缀和求出子数组之和,与s比较并更新答案
classSolution: """ @param nums: an array of integers @param s: An integer @return: an integer representing the minimum size of subarray """ defminimumSize(self, nums, s): # write your code here n = len(nums) min_length = float("inf") sum_of_subarray = 0 j = 0 for i inrange(n): while j < n and sum_of_subarray < s: sum_of_subarray += nums[j] j += 1 if sum_of_subarray >= s: min_length = min(min_length,j - i) sum_of_subarray -= nums[i]
if min_length == float("inf"): return -1 return min_length