Problem
Given an integer n
and an integer array rounds
. We have a circular track which consists of n
sectors labeled from 1
to n
. A marathon will be held on this track, the marathon consists of m
rounds. The ith
round starts at sector rounds[i - 1]
and ends at sector rounds[i]
. For example, round 1 starts at sector rounds[0]
and ends at sector rounds[1]
Return an array of the most visited sectors sorted in ascending order.
Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
2 <= n <= 100
1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1]
for0 <= i < m
Solution
Method 1 - Simulation
Intuition
Since the marathon always moves in ascending order (counter-clockwise), the most visited sectors are those between the starting sector and the ending sector of the last round, inclusive. We can simulate the path or use modular arithmetic to find the sectors visited most often.
Approach
The marathon starts at rounds[0]
and ends at rounds[-1]
. The sectors most visited are those from rounds[0]
to rounds[-1]
(inclusive), wrapping around if needed. We can construct the answer by iterating from start to end, handling the circular nature.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— We may visit all sectors once. - 🧺 Space complexity:
O(n)
— For the result list.