Study Anything ๐ง
690. Employee Importance ๋ณธ๋ฌธ
#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 ๋ฌธ์ ๋ฅผ ๋ง์ด ํ์ด๋ณด์ง ๋ชปํด์ ์ด์ ์ ํ์๋ ๋ฌธ์ ๋ฅผ ํ ๋ฒ ์ ๋ฆฌํ๊ณ ํ์ด์ฌ ์ธ์ด๋ก ๋ค์ ํ์ด๋ณผ ์๊ฐ์ด๋ค.
'์๊ณ ๋ฆฌ์ฆ๋ฌธ์ ํ์ด > 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 |