题意:给一个员工的数据结构,保存了1.id 2.重要值 3.直接管辖的员工id。要求给出一个id,返回他和他的所有直接/间接下属的重要值之和。
solution:hash。用排序+暴力+递归的方法应该也是很好做的,但是效率肯定会受影响。使用hash只需要至多遍历一遍数组即可。
/*
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector<int> subordinates;
};
*/
class Solution {
public:
/*
访问一个元素首先在hash表中查找,没有就从i开始查找,并且把经过的元素都加入hash表。
找到队首节点,将其sub添加进q,累加res,队首出列,循环直到q为空,返回结果。
*/
int getImportance(vector<Employee*> employees, int id) {
unordered_map<int, int> hash; // id - index
queue<int> q;
int i = 0;
int res = 0;
q.push(id);
while ( !q.empty() ) {
int curr_id = q.front();
if ( hash.find(curr_id) != hash.end() ) {
for ( auto sub : employees[hash[curr_id]]-> subordinates) {
q.push(sub);
}
res += employees[hash[curr_id]]-> importance;
}
else {
for ( ; i < employees.size(); i++ ) {
hash[employees[i]->id] = i;
if ( employees[i]->id == curr_id ) {
for ( auto sub : employees[i]-> subordinates) {
q.push(sub);
}
res += employees[i]-> importance;
}
}
}
q.pop();
}
return res;
}
};submission:
本文介绍了一种高效算法,用于计算指定员工及其所有直接和间接下属的重要性总和。通过使用哈希表来存储员工信息,该算法仅需遍历一次员工列表即可完成计算。

463

被折叠的 条评论
为什么被折叠?



