情况:有点难,非暴力法看了视频讲解才能做出来
977.有序数组的平方
双指针法,用双指针从原数组两边依次挑选平方后最大的数放入新数组的最后
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
for i in range(0, len(nums)):
nums[i] = nums[i] ** 2
left = 0
right = len(nums) - 1
cur = right
result = [0] * len(nums)
while left <= right:
if nums[left] > nums[right]:
result[cur] = nums[left]
left += 1
else:
result[cur] = nums[right]
right -= 1
cur -= 1
return result
209.长度最小的子数组
用双指针维护一个滑动窗口。
首先动窗口尾部,当窗口内的和大于等于target时可以看看能不能更新最小窗口长度,然后动窗口的前端来缩小窗口长度
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
end = 0
curSum = 0
result = len(nums) + 1
start = 0
while end < len(nums):
curSum += nums[end]
while curSum >= target:
curLen = end - start + 1
result = curLen if curLen < result else result
curSum -= nums[start]
start += 1
end += 1
if result <= len(nums):
return result
else:
return 0
59.螺旋矩阵II
分别处理上、右、下、左边时都是处理[)(左闭右开区间)来保证每处只被处理一次。
通过stratx、strary、offset来缩圈
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
result = [[0 for _ in range(n)] for _ in range(n)]
stratx = 0
straty = 0
offset = 1
count = 1
for _ in range(n//2):
i = stratx
j = straty
while j < n - offset:
result[i][j] = count
count += 1
j += 1
while i < n - offset:
result[i][j] = count
count += 1
i += 1
while j > offset - 1:
result[i][j] = count
count += 1
j -= 1
while i > offset - 1:
result[i][j] = count
count += 1
i -= 1
stratx += 1
straty += 1
offset += 1
if n % 2 != 0:
result[n//2][n//2] = count
return result