输入:paths,每项是 [from, to],表示从城市 A → 城市 B。
要求:找到唯一的旅游终点站:
-
终点站是 只会作为目的地出现、但从不作为起点出现的城市
-
输入保证路线不成环,所以终点唯一
输出:终点城市的名称
思路:用一个哈希表记录所有出现过的“起点”,然后再找那个从来没有作为起点出现过的城市,它就是终点站。
复杂度:
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
unordered_map<string, string> tmp;
for (auto p:paths) {
tmp[p[0]] = p[1];
}
for (auto p:paths) {
if (tmp.find(p[1]) == tmp.end()) {
return p[1];
}
}
return "";
}
};
1106

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



