LC977有序数组的平方:
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
#前后双指针
n = len(nums)
i, j = 0, n - 1
res = [-1] * n
k = n - 1
while i <= j:
if abs(nums[i]) > abs(nums[j]):
res[k] = nums[i] * nums[i]
i += 1
else:
res[k] = nums[j] * nums[j]
j -= 1
k -= 1
return res
#暴力
for i in range(len(nums)):
nums[i] *= nums[i]
i += 1
nums.sort()
return nums
暴力解法很好想,记得i+1。双指针一头一尾,建立新result数组长度也为n,并将k设为数组最后一位。注意循环条件为i<=j。if循环中可以用绝对值或者直接平方来进行判断,i+1,j-1 。k永远-1 。时间复杂度O(N)。
LC209 长度最小的子数组:
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n = len(nums)
i, j = 0, 0
total = 0
res = float('inf')
for j in range(n):
total += nums[j]
j += 1
while total >= target:
res = min(res, j - i)
total -= nums[i]
i += 1
return res if res != float('inf') else 0
滑动窗口!想好窗口的起始位置和终止位置,j为终止位置!
LC59螺旋矩阵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
绕!掌握循环不变量,定义好区间!
生成一维数组:[0] * n 或者 [0 for _ in range(n)]
生成二维数组:[[0] * m for _ in range(n)] 或者 [[0 for _ in range(m)] for _ in range(n)]
要使用range()函数逆序遍历需注意 (x, y , -1)-1!!!!!!!!!!!!