0
点赞
收藏
分享

微信扫一扫

Leetcode 1560. 圆形赛道上经过次数最多的扇区(这道题不错)

Leetcode 1560. 圆形赛道上经过次数最多的扇区(这道题不错)_升序
给你一个整数 n 和一个整数数组 rounds 。有一条圆形赛道由 n 个扇区组成,扇区编号从 1 到 n 。现将在这条赛道上举办一场马拉松比赛,该马拉松全程由 m 个阶段组成。其中,第 i 个阶段将会从扇区 rounds[i - 1] 开始,到扇区 rounds[i] 结束。举例来说,第 1 阶段从 rounds[0] 开始,到 rounds[1] 结束。

请你以数组形式返回经过次数最多的那几个扇区,按扇区编号 升序 排列。

注意,赛道按扇区编号升序逆时针形成一个圆(请参见第一个示例)。

示例 1:

Leetcode 1560. 圆形赛道上经过次数最多的扇区(这道题不错)_数组_02

输入:n = 4, rounds = [1,3,1,2]
输出:[1,2]
解释:本场马拉松比赛从扇区 1 开始。经过各个扇区的次序如下所示:
1 --> 2 --> 3(阶段 1 结束)--> 4 --> 1(阶段 2 结束)--> 2(阶段 3 结束,即本场马拉松结束)
其中,扇区 1 2 都经过了两次,它们是经过次数最多的两个扇区。扇区 3 4 都只经过了一次。

示例 2:

输入:n = 2, rounds = [2,1,2,1,2,1,2,1,2]
输出:[2]

示例 3:

输入:n = 7, rounds = [1,3,5,7]
输出:[1,2,3,4,5,6,7]

提示:

  • 2 <= n <= 100
  • 1 <= m <= 100
  • rounds.length == m + 1
  • 1 <= rounds[i] <= n
  • rounds[i] != rounds[i + 1] ,其中 0 <= i < m

主要思路:利用map统计次数(map对value进行排序)
Code:

class Solution {
public:
typedef pair<int, int> PAIR;
struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
return lhs.second > rhs.second;
}
};
vector<int> mostVisited(int n, vector<int>& rounds) {
map<int,int>mymap;
vector<int> res;
for(int i=0;i<rounds.size()-1;i++)
{

if(i==0)
{
if(rounds[i]<rounds[i+1])
{
for(int j=rounds[i];j<=rounds[i+1];j++)
{

mymap[j]++;
}
}
else
{
for(int j=rounds[i];j<=n;j++)
{

mymap[j]++;
}
for(int j=1;j<=rounds[i+1];j++)
{

mymap[j]++;
}
}
}
else
{
if(rounds[i]<rounds[i+1])
{
for(int j=rounds[i]+1;j<=rounds[i+1];j++)
{

mymap[j]++;
}
}
else
{
for(int j=rounds[i]+1;j<=n;j++)
{

mymap[j]++;
}
for(int j=1;j<=rounds[i+1];j++)
{

mymap[j]++;
}
}
}
}
//对vector排序
//把map中元素转存到vector中
vector<PAIR> name_score_vec(mymap.begin(), mymap.end());

//对vector排序
sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());

int max=name_score_vec[0].second;
res.push_back(name_score_vec[0].first);
for (int i = 1; i != name_score_vec.size(); ++i) {
if(name_score_vec[i].second<max)
break;
else
res.push_back(name_score_vec[i].first);
//可在此对按value排完序之后进行操作
// cout << name_score_vec[i].first <<" "<< name_score_vec[i].second << endl;
}
sort(res.begin(),res.end());
return res;


}
};


举报

相关推荐

0 条评论