977. Squares of a Sorted Array - LeetCode
双指针法
数组首位两个指针,比较大小添加值到res
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
# Double pointer
left = 0
right = len(nums) - 1
res = []
while left <= right:
if nums[left]*nums[left] <= nums[right]*nums[right]:
res.insert(0, nums[right]*nums[right])
right -= 1
else:
res.insert(0, nums[left]*nums[left])
left += 1
return res
209. Minimum Size Subarray Sum - LeetCode
滑动窗口
根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将O(n^2)暴力解法降为O(n)
当窗口内的值和大于target时,不断调整startPoint的位置,更新res
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
res = float(inf)
subSum = 0 # Sum of values of the sliding window
subLength = 0 # Length of sliding window
startPoint = 0
for endPoint in range(len(nums)):
subSum += nums[endPoint]
while subSum >= target:
subLength = endPoint - startPoint + 1 # Length of the subsequence
res = min(res, subLength)
subSum -= nums[startPoint]
startPoint += 1 # Change the startPoint of subsequence continuously
return res if res != float(inf) else 0
59. Spiral Matrix II - LeetCode
模拟过程
这道题就是模拟数字填入矩阵的过程,关键点在于要保持每一轮每一条边的起始点和长度
用offset控制每轮的长度,当n为4,第一轮每条边输入3次;第二轮每条边输入1次
每条边的输入范围都是左闭右开
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0]*n for _ in range(n)]
startX = 0
startY = 0
loop = n // 2
offset = 1
count = 1
while loop != 0:
x = startX
y = startY
# up-row, left close right open
for _ in range(n - offset):
res[startX][y] = count
y += 1
count += 1
# right-col, left close right open
for _ in range(n - offset):
res[x][y] = count
x += 1
count += 1
# bottom-row, left close right open
for _ in range(n - offset):
res[x][y] = count
y -= 1
count += 1
# left-col, left close right open
for _ in range(n - offset):
res[x][y] = count
x -= 1
count += 1
loop -= 1
offset += 2
# start point in next loop
startX += 1
startY += 1
# if n is odd, assign value to the middle of matrix alone
if n % 2 != 0:
res[n // 2][n // 2] = n*n
return res