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.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
这道题采用暴力求解,产生超时,因此考虑使用双指针法,区间两端分别进行扩充。时间复杂度是O(N)
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
sum = 0
j = -1
for i in range(0, len(nums)):
sum += nums[i]
if sum >= s:
j = i
break
if j == -1:
return 0
elif j == 0:
return 1
i = 0
min = j - i + 1
while (i <= j and j < len(nums)):
if sum >= s:
if (j - i + 1) < min:
min = j - i + 1
sum -= nums[i] # 相当于i后移动
i += 1
else:
j += 1
if (j)<len(nums):
sum += nums[j]
return min
进一步优化一下:
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
if len(nums)==0 or sum(nums)<s:
return 0
i = 0
j = 0
min = len(nums)
sums = nums[0]
while (i <= j and j < len(nums)):
if sums >= s:
if (j - i + 1) < min:
min = j - i + 1
sums -= nums[i] # 相当于i后移动
i += 1
else:
j += 1
if (j)<len(nums):
sums += nums[j]
return min
类似题目:
581. Shortest Unsorted Continuous Subarray
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
也是采用首尾双指针法
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sortnums = sorted(nums)
begin = 0
end = 0
for i in range(len(nums)):
if sortnums[i] != nums[i]:
begin = i
break
for i in range(len(nums)-1,-1,-1):
if sortnums[i] != nums[i]:
end = i
break
if begin == end:
return 0
return end-begin+1