【1436简单】终点旅行站(2021.10.1)
1. 问题描述
给你一份旅游线路图,该线路图中的旅行线路用数组paths
表示,其中paths[i] = [cityAi,cityBi]
表示该线路将会从cityAi
直接前往cityBi
。请你找出这里旅行的终点站,即没有任何可以通往其他城市的线路的城市。
题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行重点站。
示例1:
输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
输出:"Sao Paulo"
解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> "Lima" -> "Sao Paulo" 。
示例2:
输入:paths = [["B","C"],["D","B"],["C","A"]]
输出:"A"
解释:所有可能的线路是:
"D" -> "B" -> "C" -> "A".
"B" -> "C" -> "A".
"C" -> "A".
"A".
显然,旅行终点站是 "A" 。
2. 解题思路
相当于寻找出度为0的那个城市节点,由于所有的cityA
的出度不为0,所以相当于寻找在cityB
中出现但是没有在cityA
中出现的那个城市。
3. 代码
提交的解题思路:
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
map<string, int> cityMap;
for(int i = 0; i < paths.size(); i++){
// 表示cityMap中还没有记录该城市
if(cityMap.count(paths[i][0]) == 0){
cityMap[paths[i][0]] = 1;
} else {
cityMap[paths[i][0]] = cityMap[paths[i][0]] + 1;
}
//
if(cityMap.count(paths[i][1]) == 0){
cityMap[paths[i][1]] = 0;
}
}
// 对cityMap进行遍历,找出value为0的点
for(map<string, int>::iterator it = cityMap.begin(); it != cityMap.end(); it++){
if(it -> second == 0){
return it -> first;
}
}
return "A";
}
};
优化后:
这里使用foreach
循环和auto
关键字对上面的代码进行优化:
unordered_map与map的比较:
1.unordered_map是无序的。
2.unordered_map的查找速度比map更快。
3.但是unordered_map的内存消耗更大一些。
4.unordered_map底层使用哈希表实现,map底层使用红黑树实现。
class Solution {
public:
// 这里使用了unordered_map,与map相比,map的底层是使用红黑树实现的,而unordered_map是使用哈希表实现的
// 特点:
// 1.unordered_map是无序的
// 2.unordered_map的查找速度比map更快
// 3.但是unordered_map的内存消耗更大一些
unordered_map<string, int> cityMap;
string destCity(vector<vector<string>>& paths) {
string result = "";
for(auto p: paths){
cityMap[p[0]] = 1;
if(!cityMap[p[1]]){
cityMap[p[1]] = 2;
}
}
for(auto city: cityMap){
if(city.second == 2){
return city.first;
}
}
return result;
}
};
4. 复杂度
时间复杂度:O(n),其中n表示paths中的元素个数
空间复杂度:O(n)