977. 有序数组的平方
解法:双指针
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
right = len(nums) - 1
left = 0
cur = len(nums) - 1
ans = [-1] * len(nums)
while left <= right:
num1 = nums[left] ** 2
num2 = nums[right] ** 2
if num1 > num2:
ans[cur] = num1
left += 1
else:
ans[cur] = num2
right -= 1
cur -= 1
return ans
tips:这一题想到了用双指针法,但是没想到可以使用额外的空间存储结果。还是不够灵活。
209. 长度最小的子数组
解法:滑动窗口
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
res = float("inf")
Sum = 0
index = 0
for i in range(len(nums)):
Sum += nums[i]
while Sum >= target:
res = min(res, i-index+1)
Sum -= nums[index]
index += 1
return 0 if res==float("inf") else res
tips:能知道用滑动窗口,具体代码没有实现。index作为左边界,i作为右边界,通过for循环不断移动右边界,将下标为index-i的值加到Sum上,当Sum的值超过target时,更新res,Sum减去左边界的值,同时左边界收缩。
59. 螺旋矩阵 II
解法一:也不知道咋转出来的 居然通过了
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res = [[-1 for i in range(n)] for i in range(n)]
left, right, top, bottom = 0, n-1, 0, n-1
count = 1
while count < n*n - 1:
for i in range(left, right):
res[top][i] = count
count += 1
top += 1
print(res)
for i in range(top-1, bottom):
res[i][right] = count
count += 1
right -= 1
print(res)
for i in range(right+1, left, -1):
res[bottom][i] = count
count += 1
bottom -= 1
print(res)
for i in range(bottom+1, top-1, -1):
res[i][left] = count
count += 1
left += 1
print(res)
if n % 2 != 0:
res[n//2][n//2] = count
return res
解法二
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res = [[0] * n for i in range(n)]
x = y = 0
mid = loop = n // 2
count = 1
for offset in range(1, loop+1):
for i in range(y, n-offset):
res[x][i] = count
count += 1
for i in range(x, n-offset):
res[i][n-offset] = count
count += 1
for i in range(n-offset, y, -1):
res[n-offset][i] = count
count += 1
for i in range(n-offset, x, -1):
res[i][y] = count
count += 1
x += 1
y += 1
if n % 2 != 0:
res[mid][mid] = count
return res
最后一题转的蒙圈了。。。