LeetCode 1560. 圆形赛道上经过次数最多的扇区

1. 题目

给你一个整数 n 和一个整数数组 rounds 。有一条圆形赛道由 n 个扇区组成,扇区编号从 1 到 n 。
现将在这条赛道上举办一场马拉松比赛,该马拉松全程由 m 个阶段组成。其中,第 i 个阶段将会从扇区 rounds[i - 1] 开始,到扇区 rounds[i] 结束。举例来说,第 1 阶段从 rounds[0] 开始,到 rounds[1] 结束。

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

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

示例 1:
在这里插入图片描述

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

示例 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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-visited-sector-in-a-circular-track
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

2.1 模拟

class Solution {
public:
    vector<int> mostVisited(int n, vector<int>& rounds) {
    	vector<int> count(n, 0);
        int s = rounds[0]-1, e;
    	for(int i = 0; i < rounds.size()-1; ++i)
    	{
            e = rounds[i+1]-1;
    		while(s != e)
    		{
    			count[s]++;
    			s++;
    			if(s == n)
    				s = 0;
    		}
            count[s]++;
            s = (e+1)%n;
    	}
    	int maxcount = *max_element(count.begin(), count.end());
    	vector<int> ans;
    	for(int i = 0; i < n; i++)
    	{
    		if(count[i] == maxcount)
    			ans.push_back(i+1);
    	}
    	return ans;
    }
};

4 ms 11.2 MB

2.2 脑筋急转弯

  • 答案只跟起点和终点有关
class Solution {
public:
    vector<int> mostVisited(int n, vector<int>& rounds) {
    	vector<int> ans;
        int len = rounds.size();
        if(rounds[0] <= rounds[len-1])
        {
            for(int i = rounds[0]; i <= rounds[len-1]; i++)
                ans.push_back(i);   
        }
    	else
        {
            for(int i = 1; i <= rounds[len-1]; i++)
                ans.push_back(i);
            for(int i = rounds[0]; i <= n; i++)
                ans.push_back(i);
        }
    	return ans;
    }
};

我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/108181426