Study Anything ๐Ÿง

690. Employee Importance ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜๋ฌธ์ œ ํ’€์ด/LeetCode

690. Employee Importance

์†” 2022. 3. 23. 23:08

#HashTable #DFS #BFS

 

์ง์›์˜ ๊ณ ์œ  ID์™€ ์ค‘์š”๋„, ๋ถ€ํ•˜ ์ง์›์˜ ID๋ฅผ ํฌํ•จํ•œ ์ง์› ์ •๋ณด์˜ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๊ฐ€ ์žˆ๋‹ค.

์ง์› ๋ฐฐ์—ด employees๋Š” ๋‹ค์Œ์˜ ํŠน์ง•์„ ๊ฐ€์ง„๋‹ค.

- employees[i].id ๋Š” i๋ฒˆ์งธ ์ง์›์˜ ID์ด๋‹ค.
- employees[i].importance ๋Š” i๋ฒˆ์งธ ์ง์›์˜ ์ค‘์š”๋„ ๊ฐ’์ด๋‹ค.
- employees[i].subsciates ๋Š” i๋ฒˆ์งธ ์ง์›์˜ ๋ถ€ํ•˜ ์ง์› ID ์˜ ๋ชฉ๋ก์ด๋‹ค.


์ง์›์˜ ID๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” id๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ ์ด ์ง์›๊ณผ ๋ชจ๋“  ์ง๊ฐ„์ ‘์ ์ธ ๋ถ€ํ•˜ ์ง์›์˜ ์ด ์ค‘์š”๋„ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.


Trial 1 : Java, 21/02/19

/*
// Definition for Employee.
class Employee {
    public int id;
    public int importance;
    public List<Integer> subordinates;
};
*/

class Solution {
    Map<Integer, Employee> map;
    public int getImportance(List<Employee> employees, int id) {
        int sum = 0;
        
        if(employees==null)
            return 0;
        
        map = new HashMap<>();
        for(int i=0; i<employees.size(); i++) {
            map.put(employees.get(i).id, employees.get(i));
        }
        
        if(!map.containsKey(id))
            return 0;
        
        return dfs(id);
    }
    
    public int dfs(int id) {
        Employee emp = map.get(id);
        int sum = emp.importance;
        for(int j=0; j<emp.subordinates.size(); j++) {
            sum += dfs(emp.subordinates.get(j));
        }
        
        return sum;
    }
}

ํ’€์ด:

์ถ”ํ›„ ์ •๋ฆฌ ์˜ˆ์ •

 

๋ฆฌ๋ทฐ: 

๋Ÿฐํƒ€์ž„ 98.91%, ๋ฉ”๋ชจ๋ฆฌ 98.87% ์˜ ์„ฑ๋Šฅ์œผ๋กœ ์˜ˆ์ „์— ์ž๋ฐ” ์–ธ์–ด๋กœ ํ’€์—ˆ๋˜ DFS ๋ฌธ์ œ์ด๋‹ค.

Hash Map์„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ์ œ์˜€๊ณ  ์นดํ…Œ๊ณ ๋ฆฌ์—๋Š” BFS ๋„ ํ•จ๊ป˜ ์žˆ์—ˆ์ง€๋งŒ DFS ๋กœ ํ’€์–ด๋ณด์•˜๋‹ค.

์•„์ง ํŒŒ์ด์ฌ์œผ๋กœ๋Š” DFS ๋ฌธ์ œ๋ฅผ ๋งŽ์ด ํ’€์–ด๋ณด์ง€ ๋ชปํ•ด์„œ ์ด์ „์— ํ’€์—ˆ๋˜ ๋ฌธ์ œ๋ฅผ ํ•œ ๋ฒˆ ์ •๋ฆฌํ•˜๊ณ  ํŒŒ์ด์ฌ ์–ธ์–ด๋กœ ๋‹ค์‹œ ํ’€์–ด๋ณผ ์ƒ๊ฐ์ด๋‹ค.

 

 

728x90

'์•Œ๊ณ ๋ฆฌ์ฆ˜๋ฌธ์ œ ํ’€์ด > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

1249. Minimum Remove to Make Valid Parentheses  (0) 2022.03.15
1470. Shuffle the Array  (0) 2022.03.10
118. Pascal's Triangle  (0) 2022.03.08
413. Arithmetic Slices  (0) 2022.03.04
804. Unique Morse Code Words  (0) 2022.02.27
Comments