原题
题目大意及思路
- 题目大意: 给定一个正整数n,和一个rounds数组。n代表马拉松的站点标号为1-N,rounds数组的意义:第i段路程的起点为rounds[i-1],终点为rounds[i]。
- 思路: 用map存储每个站点的访问次数,最后找出访问最多的站点们~
代码
class Solution {
public:
vector<int> mostVisited(int n, vector<int>& rounds) {
int i=0;
map<int,int> ans;
vector<int> ansv;
int maxvisit=0;
ans[rounds[0]]++;
while(++i!=rounds.size()){
int start=rounds[i-1],end=rounds[i];
if(end>start){
while(start<end){
start++;
ans[start]++;
}
}
else if(end<start){
while(start!=end){
if(start==n) start=1;
else start++;
ans[start]++;
}
}
}
for(auto it=ans.begin();it!=ans.end();it++){
if(it->second>maxvisit){
maxvisit=it->second;
ansv.clear();
ansv.push_back(it->first);
}
else if(it->second==maxvisit) ansv.push_back(it->first);
}
return ansv;
}
};
运行截图
收获
最后又去看了leetcode官方题解。
实在是…太妙了!