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);
        }
    }
}

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

相关推荐
lisw0520 小时前
稀疏算法概述!
算法·机器人·无人机
qq_4523962320 小时前
第三篇:Transactional Outbox 模式详解
java·kubernetes·rocketmq
30955666620 小时前
股票接口重试怎么分类:正常、空数组与错误响应的幂等处理
java·大数据·开发语言·数据库·php·api接口·股票数据api接口
YLCHUP21 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴1 天前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu1 天前
python:Logistic Regression
开发语言·后端·python·算法
摇滚侠1 天前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
geovindu1 天前
python: Random Forest
开发语言·后端·python·算法·随机森林
.道阻且长.1 天前
Linux基础IO:理解文件以及回顾C文件接口
linux·运维·服务器·c语言·开发语言·职场和发展