leetcode 5495. 圆形赛道上经过次数最多的扇区(周赛203)

【题目】5495. 圆形赛道上经过次数最多的扇区

给你一个整数 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 结束,即本场马拉松结束)
其中,扇区 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

【解题思路1】模拟(没必要)

class Solution {
    
    
    public List<Integer> mostVisited(int n, int[] rounds) {
    
    
        int[] count = new int[n];
        int max = 0;
        int m = rounds.length;
        for(int i = 1; i < m; i++) {
    
    
            int start = rounds[i - 1];
            int len = (rounds[i] - start + n) % n;
            for(int j = 1; j <= len; j++) {
    
    
                count[start % n]++;
                max = Math.max(max, count[start % n]);
                start++;
            }
        }
        count[rounds[m - 1] % n]++;
        max = Math.max(max, count[rounds[m - 1] % n]);
        
        List<Integer> ans = new ArrayList<>();
        for(int i = 1; i < n; i++) {
    
    
            if(count[i] == max) {
    
    
                ans.add(i);
            }
        }
        if(count[0] == max)     ans.add(n);
        return ans;
    }
}

【解题思路2】只关注开头和结尾

对于跑赛道来说,不需要关注跑了几圈,或者中途经历了什么,
从1开始跑到4 不管几圈 所有位置的经历次数一样
从1开始跑到3 说明 只有4 少了一次 则扇区1 3 4为最大次数扇区
从1开始跑到2 说明 3 4少了一次

class Solution {
    
    
    public List<Integer> mostVisited(int n, int[] rounds) {
    
    
        List<Integer> ans = new ArrayList<Integer>();
        int s = rounds[0];
        int e = rounds[rounds.length-1];
        if (s <= e){
    
    
            for (int i = s; i <= e; i++){
    
    
                ans.add(i);
            }
        }else {
    
    
            for (int i = 1; i <= e; i++){
    
    
                ans.add(i);
            }
            for (int i = s; i <= n; i++){
    
    
                ans.add(i);
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/XunCiy/article/details/108181934
今日推荐