day2
#977 有序数组的平方
使用双指针解决
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
length = len(nums)
left, right = 0, length -1
result = []
while left <= right:
if abs(nums[left]) >= nums[right]:
result.append(nums[left]**2)
left += 1
else:
result.append(nums[right]**2)
right -= 1
return result[::-1]
# 209.长度最小的子数组
滑动窗口&快慢指针区别:
快慢:用于链表,会相遇
此处要考虑到无的情况,所以初始result是float("inf")
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
fast = 0
slow = 0
length = len(nums)
result = float("inf")
check = 0
# 区分range(len())和[:len()+1]
for fast in range(len(nums)):
check += nums[fast]
while check >= target:
result = min(result, fast-slow+1)
check -= nums[slow]
slow += 1
return result if result != float("inf") else 0
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):
for j in range(starty, n-offset):
nums[startx][j] = count
count += 1
for i in range(startx, n-offset):
nums[i][n-offset] = count
count += 1
for j in range(n-offset, starty, -1):
nums[n-offset][j] = count
count += 1
for i in range(n-offset, startx, -1):
nums[i][startx] = count
count += 1
startx += 1
starty += 1
if n % 2 == 1:
nums[startx][starty] = count
return nums
1. 对于已知的列表、矩阵,可以直接创建。[[0]*n for _ in range(n)] 长度为n,创建n次
2. 对于这道题,需要确定 (1)循环次数(用于确定长度);(2)每次循环的出发点。这两个即可。
3. 特例,如果为奇数,最后会剩余一个,需要额外运行。