class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
l = len(nums)
left = 0
right = 0
min_len = float('inf')
cur_sum = 0 #当前的累加值
while right < l:
cur_sum += nums[right]
while cur_sum >= s: # 当前累加值大于目标值
min_len = min(min_len, right - left + 1)
cur_sum -= nums[left]
left += 1
right += 1
return min_len if min_len != float('inf') else 0
不知道为什莫写出来答案不一样,先记录一下
#给定一个含有 n 个正整数的数组和一个正整数 target 。
#找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0
from typing import List
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
l = len(nums)
left = 0
right = 0
min_len = float('inf')#正无穷
cur_sum = 0 #累加值
while right < 1:
cur_sum += nums[right]
while cur_sum >= s: #当前累加值大于目标值
min_len = min(min_len,right - left + 1)
cur_sum -= nums[left]
left += 1
right += 1
return min_len if min_len != float('inf') else 0
s = 7
nums = [2,3,1,2,4,3]
solution=Solution()
solution.minSubArrayLen(target,nums)
用双指针来实现有序数组的平方
from typing import List
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
l = 0
r = len(nums)-1
res = [0]*len(nums)
n = len(nums)-1
while l < r:
if nums[l]*nums[l] < nums[r]*nums[r]:
res[n]=nums[r]*nums[r]
r -=1
else:
res[n]=nums[l]*nums[l]
l += 1
n -= 1
return res
nums = [-7,-3,2,3,11]
solution = Solution()
solution.sortedSquares(nums)
螺旋矩阵不大会,先看题和思路
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums = [[0] * n for _ in range(n)]
startx, starty = 0, 0 # 起始点
loop, mid = n // 2, n // 2 # 迭代次数、n为奇数时,矩阵的中心点
count = 1 # 计数
for offset in range(1, loop + 1) : # 每循环一层偏移量加1,偏移量从1开始
for i in range(starty, n - offset) : # 从左至右,左闭右开
nums[startx][i] = count
count += 1
for i in range(startx, n - offset) : # 从上至下
nums[i][n - offset] = count
count += 1
for i in range(n - offset, starty, -1) : # 从右至左
nums[n - offset][i] = count
count += 1
for i in range(n - offset, startx, -1) : # 从下至上
nums[i][starty] = count
count += 1
startx += 1 # 更新起始点
starty += 1
if n % 2 != 0 : # n为奇数时,填充中心点
nums[mid][mid] = count
return nums