当前位置:网站首页>leetcode:剑指 Offer II 115. 重建序列【图论思维 + 入度考虑 + 拓扑排序】
leetcode:剑指 Offer II 115. 重建序列【图论思维 + 入度考虑 + 拓扑排序】
2022-07-23 15:33:00 【白速龙王的回眸】

分析
这种子序列的有严格的先后顺序,可考虑成边
然后进行拓扑排序,看看是否唯一
对sequences的相邻两点,我们可以存边和计算入度
然后建一个queue,放入入度为0的
显然,只能有一个入度为0的,否则多种选择
然后对于queue中的,我们找他的下一个点,入度为1的
这些入度为1的必须紧跟在后面,而且只能有1个,否则面临多种选择。。。
ac code
class Solution:
def sequenceReconstruction(self, nums: List[int], sequences: List[List[int]]) -> bool:
# 关于图论和入度
n = len(nums)
inDeg = [inf] + [0] * n
g = defaultdict(list)
for sequence in sequences:
for x, y in pairwise(sequence):
g[x].append(y)
inDeg[y] += 1
# q存入度为0的
q = deque([i for i, degrees in enumerate(inDeg) if degrees == 0])
while q:
# 多个选择
if len(q) > 1:
return False
x = q.popleft()
for y in g[x]:
degree = inDeg[y]
if inDeg[y] == 1:
#inDeg[y] -= 1
q.append(y)
return True
总结
顺序问题转成图论的拓扑排序问题
考虑入度为1的只能选一个
边栏推荐
- ContextLoaderListener vs DispatcherServlet
- Solution to connection rejected error in idea download sources
- WSUS can patch MySQL Middleware_ Join the WSUS patch server and download the patch
- isEmpty 和 isBlank 的用法区别,至少一半的人答不上来...
- MYSQL基础及性能优化
- 数智化时代文旅遇新机?中国移动咪咕造 “元宇宙第一岛”
- sns_ sensor_ instance_ api
- Mongodb group one piece of data in each group
- Rust中的函数function与方法method的区别
- Transfer business append log (transaction propagation behavior)
猜你喜欢
Do you dare to use BigDecimal without mastering these pits?

idea debug常用操作

工業物聯網中的時序數據

Solutions to sap Hana database backup failure

ContextLoaderListener vs DispatcherServlet

TwinCAT 3 首次运行报错4115

Deeply understand the mode and vibration of mechanical system

USB Type-C PD CC逻辑芯片中的角色定义

Research and implementation of network multi exit design based on policy routing deployment

MYSQL基础及性能优化
随机推荐
SAP HANA数据库备份失败解决办法
Trust guessing numbers game
Use Preparedstatement to select and display recorded JDBC programs
Date formatting
Leetcode skimming: dynamic programming 05 (different paths II)
Static distribution and dynamic distribution in trust
Solution to connection rejected error in idea download sources
活动报名:如何零基础快速上手开源的 Tapdata Live Data Platform?
ride the wind and waves! Digital transformation in the era of financial technology
PDO operation
分布式事务解决方案
Deeply understand the mode and vibration of mechanical system
基于策略路由部署的网络多出口设计研究与实现
From 5 seconds to 1 second, remember the performance optimization with "very" significant effect once
As a background developer, you must know two kinds of filters
c语言--通讯录的实现与ScreenToGif
ContextLoaderListener vs DispatcherServlet
Research and implementation of network multi exit design based on policy routing deployment
TP & smart use diary
@Will multiple bean instances be created by multiple method calls of bean annotations