这个题吧,相当复杂,需要你熟练掌握C++容器。
下面是乐乐自己总结的备忘录吧:以后有机会公布电子版的xmind:
image.png
单纯看代码有点累,而且我也是怎么也看不懂,还是放在VS 里面单步调试一点点分析:
以下是实例与运行过程:
image.png
- code:
//lintcode 1070
//my
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
unordered_map<string, vector<int>> map;
set<string> s;
queue<int> q;
int n = accounts.size();
vector<int> visited(n, 0);
vector<vector<string>> ans;
for (int i = 0; i < n; i++) {
for (int j = 1; j < accounts[i].size(); j++) {
map[accounts[i][j]].push_back(i);
}
}
for (int i = 0; i < n; i++) {
if (visited[i] == 0) {
q.push(i);
s.clear();
while (!q.empty()) {
int temp = q.front();
q.pop();
visited[temp] = 1;
vector<string> newmail(accounts[temp].begin() + 1, accounts[temp].end());
for (auto mm : newmail) {
s.insert(mm);
for (auto aa : map[mm]) {
if (visited[aa] == 0) {
q.push(aa);
visited[aa] = 1;
}
}
}
}
vector<string> out(s.begin(), s.end());
out.insert(out.begin(), accounts[i][0]);
ans.push_back(out);
}
}
return ans;
}
网友评论