977 有序数组的平方
- 双指针
-
class Solution(object): def sortedSquares(self, nums): left = 0 right = len(nums) - 1 ans = [0 for _ in range(len(nums))] for i in range(len(nums)-1, -1, -1): if abs(nums[left]) > abs(nums[right]): ans[i] = nums[left] ** 2 left += 1 else: ans[i] = nums[right] ** 2 right -= 1 return ans
- 时间复杂度:O(n)
- 空间复杂度:O(n)
209 长度最小的数组
- 双指针(滑动窗口)
-
class Solution(object): def minSubArrayLen(self, target, nums): i = j = total = 0 ans = len(nums) + 1 while j < len(nums): total += nums[j] while total >= target: ans = min(ans, j - i + 1) total -= nums[i] i += 1 j += 1 return ans if ans <= len(nums) else 0
- 时间复杂度:O(n)
- 空间复杂度:O(1)
59 螺旋矩阵II
- top, down, left, right
-
class Solution(object): def generateMatrix(self, n): matrix = [[0 for _ in range(n)] for _ in range(n)] top, down, left, right = 0, n-1, 0, n-1 num = 1 while left <= right and top <= down: for j in range(left, right+1): matrix[top][j] = num num += 1 top += 1 for i in range(top, down+1): matrix[i][right] = num num += 1 right -= 1 for j in range(right, left-1, -1): matrix[down][j] = num num += 1 down -= 1 for i in range(down, top-1, -1): matrix[i][left] = num num += 1 left += 1 return matrix
- 时间复杂度:O(n^2)
- 空间复杂度:O(1)