2024.4.7力扣每日一题——王位继承顺序

题目来源

力扣每日一题;题序:1600

我的题解

方法一 哈希表+多叉树的前序遍历

发现继承顺序的生成与多叉树的前序遍历一致,只需要在遍历过程中将已经去世的给排除就可以了。
如何存储继承关系?使用哈希表[父亲,儿子集合]
需要额外存储已经过世的人。注:有坑!!!!使用List要超时,只能使用Set

时间复杂度

  • ThroneInheritance(kingName):O(1);
  • birth(parentName, childName):O(1);
  • death(name):O(1);
  • getInheritanceOrder():O(n),其中 n 是当前树中的总人数。需要对整棵树进行一次前序遍历,时间复杂度为 O(n)。
    空间复杂度:O(n)。
class ThroneInheritance {
    Map<String,List<String>> parent;
    Set<String> hasDead;
    String king;
    public ThroneInheritance(String kingName) {
        king=kingName;
        parent=new HashMap<>();
        hasDead=new HashSet<>();
    }
    
    public void birth(String parentName, String childName) {
        if(!hasDead.contains(parentName)){
            List<String> l=parent.getOrDefault(parentName,new ArrayList<>());
            l.add(childName);
            parent.put(parentName,l);
        }
    }
    
    public void death(String name) {
        hasDead.add(name);
    }
    
    public List<String> getInheritanceOrder() {
        List<String> res=new ArrayList<>();
        dfs(king,res);
        return res;
    }
    public void dfs(String p,List<String> res){
        if(!hasDead.contains(p))
            res.add(p);
        for(String s:parent.getOrDefault(p,new ArrayList<>())){
            dfs(s,res);
        }
    }
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐

  1. 2024.4.7每日——王位继承顺序

    2024-04-09 23:50:01       14 阅读
  2. 每日:课程表Ⅱ

    2024-04-09 23:50:01       45 阅读
  3. 每日 6/6

    2024-04-09 23:50:01       11 阅读
  4. 每日 6/7

    2024-04-09 23:50:01       9 阅读
  5. 每日 6/5

    2024-04-09 23:50:01       9 阅读
  6. 每日 6/8

    2024-04-09 23:50:01       8 阅读
  7. 每日-881

    2024-04-09 23:50:01       5 阅读
  8. 每日383赎金信

    2024-04-09 23:50:01       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-09 23:50:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-09 23:50:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-09 23:50:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-09 23:50:01       20 阅读

热门阅读

  1. python--异常处理

    2024-04-09 23:50:01       20 阅读
  2. QB/T 4464-2013 家具用蜂窝板检测

    2024-04-09 23:50:01       15 阅读
  3. vue3基础: 组件注册

    2024-04-09 23:50:01       12 阅读
  4. 微信小程序第六次课(模块化和绑定事件)

    2024-04-09 23:50:01       14 阅读
  5. 题目 2915: 接水问题

    2024-04-09 23:50:01       18 阅读
  6. GDB调试概述

    2024-04-09 23:50:01       13 阅读
  7. 题目 2016: 新生的入队仪式

    2024-04-09 23:50:01       13 阅读
  8. 三月已过,春招进度堪忧

    2024-04-09 23:50:01       14 阅读
  9. 并查集(基础+带权以及可撤销并查集后期更新)

    2024-04-09 23:50:01       14 阅读
  10. Linux 内核同步

    2024-04-09 23:50:01       15 阅读