977. 有序数组的平方
利用双指针一左一右向中间移动
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
left, right, i = 0, len(nums) - 1, len(nums) - 1 #定义左右指针
result = [float('inf')] * len(nums) #定义空数组存放结果
while left <= right:
if nums[left] ** 2 < nums[right] ** 2:
result[i] = nums[right] ** 2
right -= 1
else:
result[i] = nums[left] ** 2
left += 1
i -= 1
return result
209. 长度最小的数组
利用双指针求得题目所需长度最短的数组
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left, right = 0, 0 #定义双指针
min_len = float('inf')
sum = 0
while right < len(nums): #右指针向右移动使sum增加
sum += nums[right]
while sum >= target: #当sum达到要求后开始减小左右指针间距
min_len = min(min_len, right - left + 1)
sum -= nums[left]
left += 1
right += 1
return min_len if min_len != float('inf') else 0 #处理特殊情况:数组所有元素和小于target返回0
59.螺旋矩阵II
个人感觉该题小有难度,边界判断很多,经常把自己绕进去,之后再研究一下
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums = [[0] * n for _ in range(n)]
x, y = 0, 0
loop, mid = n // 2, n // 2
count = 1
for offset in range(1, loop + 1):
for i in range(y, n - offset):
nums[x][i] = count
count += 1
for i in range(x, n - offset):
nums[i][n - offset] = count
count += 1
for i in range(n - offset, y, -1):
nums[n - offset][i] = count
count += 1
for i in range(n - offset, x, -1):
nums[i][y] = count
count += 1
x += 1
y += 1
if n % 2 != 0:
nums[mid][mid] = count
return nums
参考文档:代码随想录