1. 题目来源
链接:5400. 旅行终点站
2. 题目说明
3. 题目解析
方法一:暴力+常规解法
签到题,暴力思路如下:
- 采用
map<string, string>
存储起点终点 - 两层
for
循环统计每个终点,是否有作为起点的情况,若没有就说明这个终点是最终答案,返回即可
时间复杂度为 O ( n 2 ) O(n^2) O(n2),时间复杂度较高,也是我的第一思路吧,就顺顺利利的敲出来了。
参见代码如下:
// 执行用时 :52 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :11.3 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
map<string, string> m;
for (int i = 0; i < paths.size(); ++i) {
m[paths[i][0]] = paths[i][1];
}
for (auto e : m) {
int flag = 0, cnt = 0;
for (auto s:m) {
if (e.second == s.first) break;
++cnt;
}
if (cnt == m.size()) return e.second;
}
return "";
}
};
方法二:暴力+图+常规解法
很容易能将问题抽象为图,那么就是查看是否存在城市点的出度为 0,即为所求答案。 可以采用 map<string, int>
来维护城市及对应的出度。用 set
来维护所有城市即可。时间复杂度为
O
(
n
)
O(n)
O(n)。
参见代码如下:
// 执行用时 :44 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :12.1 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
map<string, int> m;
set<string> s;
for (auto e : paths) {
m[e[0]]++;
s.insert(e[0]);
s.insert(e[1]);
}
for (auto e : s) {
if (m[e] == 0)
return e;
}
return "";
}
};