小黑代码
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
# 数组长度
n = len(nums)
# 定义双指针
head = 0
tail = 0
# 中间变量
sum_ = 0
# 结果变量
min_ = n + 1
# 开始迭代
while head < n:
# 尾部指针右移
while tail < n and sum_ < target:
sum_ += nums[tail]
tail += 1
# 记录长度
if sum_ >= target and min_ > tail - head:
min_ = tail - head
sum_ -= nums[head]
head += 1
return min_ if min_ != n + 1 else 0
小黑根据思路自己尝试前缀和二分法
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
# 数组长度
n = len(nums)
# 计算前缀和
arr = [0] + [nums[0]] * n
for i in range(1, n+1):
arr[i] = arr[i-1] + nums[i-1]
# 结果变量
res = n + 1
# 开始进行二分查找
print(arr)
for i in range(n+1):
if arr[i] < target:
continue
l = self.left_search(arr[:i], arr[i] - target)
length = i - l + 1 if arr[i] - target < arr[l] else i - l
if length < res:
res = length
return res if res != n + 1 else 0
def left_search(self, arr, target):
# 初始化双指针
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
前缀和二分法
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
# 数组长度
n = len(nums)
# 构造前缀和数组
arr = [0]
for i in range(n):
arr.append(nums[i]+arr[i])
# 开始进行二分查找大于等于arr[i]+target的最近左位置
# 结果变量
res = n + 1
for i in range(n):
end = self.left_search(arr,i+1, target+arr[i])
if end == n + 1:
continue
length = end - i
if length < res:
res = length
return res if res != n + 1 else 0
def left_search(self, arr, start, target):
n = len(arr)
# 定义左右指针
start = start
end = n - 1
while start <= end:
mid = (start + end) // 2
if arr[mid] < target:
start = mid + 1
else:
end = mid - 1
return start
双指针法
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
# 数组长度
n = len(nums)
# 中间变量
sum_ = 0
# 头尾指针
head = 0
tail = 0
# 结果变量
res = n + 1
# 开始双指针迭代
while tail < n:
sum_ += nums[tail]
tail += 1
while sum_ >= target:
if tail - head < res:
res = tail - head
sum_ -= nums[head]
head += 1
return res if res != n + 1 else 0
小黑生活
酒店早餐
补充喀纳斯的烤馕
前往那拉提空中草原,但由于天气原因景区封闭,前往河谷草原
(坐在草地上)
骑上小马
午饭,迟到团友加了菜
下午前往薰衣草基地,离调包侠不远了
入住伊宁江苏酒店
去小巷子里吃便宜的烧烤