力扣: 剑指 Offer II 115. 重建序列

该博客详细介绍了如何实现一个图的拓扑排序算法,用于判断给定的序列是否能作为图的拓扑排序结果。通过构建邻接表,计算每个节点的入度,并使用队列进行层次遍历,最终确定是否存在有效的序列重建。此算法在数据结构与图论领域具有重要意义。
摘要由CSDN通过智能技术生成
class Solution {
    public boolean sequenceReconstruction(int[] nums, int[][] sequences) {
        int n = nums.length;
        int[] indegrees  = new int[n + 1];
        Set<Integer>[] graph = new Set[n + 1];
        for (int i = 1; i <= n; i++){
            graph[i] = new HashSet<>();
        }

        for (int[] sequence : sequences) {
            int size = sequence.length;
            for (int i = 1; i < size; i++){
                int prev = sequence[i  -1], next = sequence[i];
                if (graph[prev].add(next)) {
                    indegrees[next]++;
                }
            }
        }

        Queue<Integer> queue = new ArrayDeque<>();
        // 入队
        for (int i = 1; i <= n; i++){
            if (indegrees[i] == 0){
                queue.offer(i);
            }
        }

        while (!queue.isEmpty()){
            if (queue.size() > 1){
                return  false;
            }
            int num = queue.poll();
            Set<Integer> set = graph[num];
            for (int next : set){
                indegrees[next] --;
                if (indegrees[next] == 0){
                    queue.offer(next);
                }
            }
        }
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值