2045. 到达目的地的第二短时间
BFS +剪枝
通过一个list 来记录 从i 从到该节点最近的两个距离 ,对于后续拓展到的节点不满足次最近的,就忽略,
class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
dmap = defaultdict(set)
for edge in edges:
dmap[edge[0]].add(edge[1])
dmap[edge[1]].add(edge[0])
numof =[[inf]*2 for _ in range(n+1)]
que = [(1,0)]
while que:
node,nt = que.pop(0)
if (nt//change)%2 == 1:
nt = ((nt//change)+1) *change
for ano in dmap[node]:
if nt+time <numof[ano][0]:
numof[ano][0] =nt+time
elif nt+time >numof[ano][0] and nt+time<numof[ano][1]:
numof[ano][1] =nt+time
if ano ==n:
return nt+time
else :
continue
que.append((ano,nt+time))
return -1
977. 有序数组的平方
双指针 +归并
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
res =[]
flag =0
for i in range(len(nums)):
if nums[i]>= 0:
flag = i
break
zer =nums[:i]
one =nums[i:]
while zer and one:
if (zer[-1]*zer[-1])>(one[0]*one[0]):
res.append(one[0]*one[0])
one.pop(0)
else :
res.append(zer[-1]*zer[-1])
zer.pop()
while zer:
res.append(zer[-1]*zer[-1])
zer.pop()
while one:
res.append(one[0]*one[0])
one.pop(0)
return res