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

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)。
java 复制代码
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);
        }
    }
}

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

相关推荐
小羊没烦恼!5 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
俊昭喜喜里5 天前
java中的继承和多态的区别
java
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕5 天前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码5 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖5 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
此时不提桶,更待何时5 天前
01-06-A-JVM排查实战详解
java·jvm
猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
vipxieliang5 天前
ValidX 在 DDD 领域驱动设计中的实践
java·spring boot