文章目录
1. 题目来源
链接:1396. 设计地铁系统
2. 题目说明
3. 题目解析
方法一:模拟+常规解法
很纯的模拟题,思路如下:
- 以 4 个
map
进行数据存储记录,具体功能已经注释在代码中 - 在此记录起点、终点字符串时,若采用直接字符串相加的形式进行记录会产生歧义,例如:
a
、bc
和ab
、c
,导致结果出错。所以需要采用间隔符进行唯一标识,不过好像该题没有挖这个坑。
为啥写好的博客又被我覆盖掉了…难受啊~
参见代码如下:
// 执行用时 :68 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :7.7 MB, 在所有 C++ 提交中击败了100.00%的用户
class UndergroundSystem {
public:
// 记录乘客id及上车车站
map<int, string> m_in;
// 记录旅途起点至终点的出现次数
map<string ,int> m_count;
// 记录乘客id及checkin花费时间
map<int, int> m_time;
// 记录旅途及乘客坐车时间
map<string, long long> m_dis;
UndergroundSystem() {
m_in.clear();
m_count.clear();
m_time.clear();
m_dis.clear();
}
void checkIn(int id, string stationName, int t) {
m_in[id] = stationName;
m_time[id] = t;
}
void checkOut(int id, string stationName, int t) {
string tmp = m_in[id] + "#" + stationName;
m_count[tmp]++;
m_dis[tmp] += (long long)(t - m_time[id]);
}
double getAverageTime(string startStation, string endStation) {
string tmp = startStation + "#" +endStation;
double ans = m_dis[tmp];
ans /= m_count[tmp];
return ans;
}
};
/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem* obj = new UndergroundSystem();
* obj->checkIn(id,stationName,t);
* obj->checkOut(id,stationName,t);
* double param_3 = obj->getAverageTime(startStation,endStation);
*/