977. 有序数组的平方
对于一个有序数组其两端的值才有可能是最大的值,因此只需要用双指针指示两端的值。
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
leftindex = 0
rightindex = len(nums) - 1
index = len(nums) - 1
result = [float('inf')] * len(nums)
while leftindex <= rightindex:
if nums[leftindex]**2 < nums[rightindex]**2:
result[index] = nums[rightindex]**2
rightindex -= 1
else:
result[index] = nums[leftindex]**2
leftindex += 1
index -= 1
return result
209. 长度最小的子数组
不断滑动区间使得数组的和等于目标值,保留其中的最小值。
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
leftindex, rightindex = 0,0
min_length = float('inf')
num_sum = 0
while rightindex <= len(nums) - 1:
num_sum += nums[rightindex]
while num_sum >= target:
min_length = min(min_length, rightindex - leftindex + 1)
num_sum -= nums[leftindex]
leftindex += 1
rightindex += 1
if min_length == float('inf'):
return 0
else:
return min_length
59. 螺旋矩阵II
洛谷做过这道题,就是模拟这个逻辑。
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
count = 1
for offset in range(1, loop + 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 :
nums[mid][mid] = count
return nums