690. Employee Importance

复制代码
package Leetcode_690

import java.util.*
import kotlin.collections.HashMap

/**
 * 690. Employee Importance
 * https://leetcode.com/problems/employee-importance/
 *
 * You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees employees where:
employees[i].id is the ID of the ith employee.
employees[i].importance is the importance value of the ith employee.
employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.
Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.

Example1:
Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1
Output: 11
Explanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.
They both have an importance value of 3.
Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11.

Constraints:
1 <= employees.length <= 2000
1 <= employees[i].id <= 2000
All employees[i].id are unique.
-100 <= employees[i].importance <= 100
One employee has at most one direct leader and may have several subordinates.
The IDs in employees[i].subordinates are valid IDs.
 * */

// Definition for Employee.
class Employee {
    var id: Int = 0
    var importance: Int = 0
    var subordinates: List<Int> = listOf()
}

class Solution {
    /**
     * Solution: Mapping + BFS, Time complexity:O(n), Space complexity:O(n)
     * */
    fun getImportance(employees: List<Employee?>, id: Int): Int {
        var result = 0
        val map = HashMap<Int, Employee?>()
        for (employee in employees) {
            if (employee == null) {
                continue
            }
            map.put(employee.id, employee)
        }
        val queue = LinkedList<Employee>()
        val first = map.get(id)
        queue.offer(first)
        while (queue.isNotEmpty()) {
            val top = queue.pop()
            result += top.importance
            for (item in top.subordinates) {
                queue.offer(map.get(item))
            }
        }
        return result
    }
}
复制代码

 

posted @   johnny_zhao  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-02-03 9. Palindrome Number
2019-02-03 理解Android View的事件传递机制
点击右上角即可分享
微信分享提示