LeetCode 977
暴力搜索法
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums[i] = nums[i] ** 2
nums.sort()
return(nums)
一开始甚至把sort的位置放错了,究极粗心。
双指针法
初始版本
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
result = []
r = len(nums) - 1
l = 0
while r >= l:
if nums[r] ** 2 >= nums[l] ** 2:
result.insert(0,nums[r] ** 2)
r -= 1
else:
result.insert(0,nums[l] ** 2)
l += 1
return result
整体思路基本上day1已经领会过了。
LeetCode 209 长度最小数组
先尝试for循环嵌套,一开始主要有几个问题没想清楚:一是初始sum=0放哪,这一点单纯是最近几个月没怎么碰题目手生了;二是塞完两个for循环后怎么求子链长度,稍微调试后就可以了,代码如下:
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
l = len(nums)
result = float('inf')
for i in range(l):
sumn = 0
for j in range(i,l):
sumn += nums[j]
if sumn >= target:
result = min(result,j - i + 1)
break
return result if result != float('inf') else 0
这种暴力搜索超时完全正常,一旦列表内元素都是大数字的话,测试是肯定是过不去的。
先凭借第一印象尝试写滑动窗口解法,如下,各种报错
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
sumn = 0
start = 0
subl = 0
result = float('inf')
for end in range(len(nums)):
sumn = sum(nums[start:end])
while sumn >= target:
sumn -= nums[start]
subl = end - start + 1
if subl < result:
result = subl
start += 1
if result == float('inf'):
return 0
else:
return subl
看完视频后优化成这样,通过
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
sumn = 0
start = 0
end = 0
subl = 0
result = float('inf')
while end < len(nums):
sumn += nums[end]
while sumn >= target:
sumn -= nums[start]
result = min(result,end - start + 1)
start += 1
end += 1
return result if result != float('inf') else 0
Leetcode 59.螺旋矩阵II
核心在于如何,分块,高数做递推公式时其实这一块接触的还是比较多的,所以很快消化了这一部分。其中在如何处理旋转的循环时出了点问题,重新整理了,startx,starty,offset和循环轮数的关系后成功解决问题,如下。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums = [[0] * n for _ in range(n)]
startx = 0
starty = 0
offset = 1
count = 1
for loop in range(int(n/2)):
for j in range(starty,n - offset):
nums[startx][j] = count
count += 1
for i in range(startx,n - offset):
nums[i][n - offset] = count
count += 1
for j in range(n - offset,starty,-1):
nums[n - offset][j] = count
count += 1
for i in range(n - offset,startx,-1):
nums[i][starty] = count
count += 1
startx += 1
starty += 1
offset +=1
if n % 2 != 0:
nums[startx][starty] = n ** 2
return nums
总结
初次博客,感觉还是没有太好地把解题过程中的感悟写出来,后面一步一步加强吧。