给你一个整数 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 <= 1001 <= m <= 100rounds.length == m + 11 <= rounds[i] <= nrounds[i] != rounds[i + 1],其中0 <= i < m
package Solution1560;
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> mostVisited(int n, int[] rounds) {
List<Integer> out = new ArrayList<Integer>();
int[] count = new int[n];
int start = 0;
int end = 0;
start = rounds[0];
count[start - 1]++;
for (int i = 1; i < rounds.length; i++) {
end = rounds[i];
if (end > start) {
for (int j = start + 1; j <= end; j++) {
count[j - 1]++;
}
} else {
for (int j = start + 1; j <= n; j++) {
count[j - 1]++;
}
for (int j = 1; j <= end; j++) {
count[j - 1]++;
}
}
start = end;
}
// System.out.println(Arrays.toString(count));
int max = 0;
for (int i = 0; i < count.length; i++) {
if (count[i] > max) {
max = count[i];
}
}
// System.out.println(max);
for (int i = 0; i < count.length; i++) {
if (count[i] == max) {
out.add(i + 1);
}
}
return out;
}
public static void main(String[] args) {
Solution sol = new Solution();
int n = 4;
int[] rounds = { 1, 3, 1, 2 };
System.out.println(sol.mostVisited(n, rounds));
}
}
这篇文章探讨了一场比赛中如何通过数组计算马拉松选手最常经过的扇区,涉及逆时针赛道和阶段划分。解决了一个关于路径遍历和计数的问题。
247

被折叠的 条评论
为什么被折叠?



