一、题目链接
二、学习跟练视频链接
【矩阵快速幂优化 DP【力扣周赛 362】】 https://www.bilibili.com/video/BV1U34y1N7Pe/?share_source=copy_web&vd_source=dc0e55cfae3b304619670a78444fd795
三、代码
1.第一题
题目:2848. 与车相交的点
解题:
差分数组
使用差分数组将区间变化转化为两个点变化。
class Solution:
def numberOfPoints(self, nums: List[List[int]]) -> int:
# 自写代码
cnt = [0] * 102 # 0位和101位无用,101位防止越界
ans = 0
for i in nums:
cnt[i[0]] += 1
cnt[i[1]+1] -= 1
for i in range(1,101):
cnt[i] += cnt[i-1]
if cnt[i] != 0:
ans += 1
return ans
参考视频代码,对两处进行修改。1.差分数组长度;2.将差分数组还原成原数组的部分。修改后代码如下:
class Solution:
def numberOfPoints(self, nums: List[List[int]]) -> int:
# 参考修改后代码
max_end = max([end for _,end in nums])
cnt = [0] * (max_end+2) # 差分数组,0位和101位无用,101位防止越界
for i in nums:
cnt[i[0]] += 1
cnt[i[1]+1] -= 1
return sum(s>0 for s in itertools.accumulate(cnt))
2024.3.11续:
2.第二题
解题:
运用数学方法
class Solution:
def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool:
x = abs(fx - sx) # x的变化值
y = abs(fy - sy) # y的变化值
# 先能走斜线尽量斜线,那么最少的步数就是max(x,y)
if t >= max(x,y): # t必须大于等于最少步数,不然无法满足
if x == y == 0 and t == 1:
# 多余的步数都可以绕圈来满足,但是当目标位置是原地时,仅走一步是没法满足的
return False
return True
return False
3.第三题:
解题:
暴力枚举+全排列
本题博主不会,根据视频讲解学习,代码为跟练视频代码
class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
# 灵神方法 暴力枚举 全排列
from_ = [] # 存需要拿出位置的坐标
to = [] # 存需要放入的位置的坐标
for i,row in enumerate(grid): # 存
for j,cnt in enumerate(row):
if cnt > 1:
from_.extend([(i,j)] * (cnt - 1))
elif cnt == 0:
to.append((i,j))
ans = inf # 得最小值
for from2 in permutations(from_): #from_列表全排
total = 0 #计算总路程
for (x1,y1),(x2,y2) in zip(from2,to):
total += abs(x1-x2) + abs(y1-y2)
ans = min(ans,total) # 每一种组合更新
return ans
4.第四题
(未完待续)
感谢你看到这里!一起加油吧!