算法第二天
977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II
977.有序数组的平方
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: # type: ignore # # 暴力解法 # new_res = [] # for num in nums: # new_res.append(num**2) # return sorted(new_res) # 双指针解法 # 原数组nums为非递减顺序,那么平方后最大的一定在首尾位置以此类推 new_nums = [] left, right = 0, len(nums) - 1 while left <= right: if nums[left]**2 < nums[right]**2: new_nums.append(nums[right]**2) right -= 1 else: new_nums.append(nums[left]**2) left += 1 return new_nums[::-1]
209.长度最小的子数组
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: # type: ignore l = len(nums) left = 0 right = 0 min_len = float('inf') cur_sum = 0 while right < l: cur_sum += nums[right] while cur_sum >= target: min_len = min(min_len, right-left+1) cur_sum -= nums[left] left += 1 right += 1 return min_len if min_len != float('inf') else 0
59.螺旋矩阵II
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: # type: ignore nums = [[0] * n for _ in range(n)] startx, starty = 0, 0 # 起始点 loop, mid = n // 2, n // 2 # 迭代次数、n为奇数时,矩阵的中心点 count = 1 # 计数 for offset in range(1, loop + 1) : # 每循环一层偏移量加1,偏移量从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 : # n为奇数时,填充中心点 nums[mid][mid] = count return nums