Skip to content

1560. Most Visited Sector in a Circular Track 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  vector<int> mostVisited(int n, vector<int>& rounds) {
    // 1. If start <= end, [start, end] is the most visited.
    //
    //      s --------- n
    // 1 -------------- n
    // 1 ------ e
    //
    // 2. If start > end, [1, end] and [start, n] are the most visited.
    //
    //             s -- n
    // 1 -------------- n
    // 1 ------ e
    const int start = rounds.front();
    const int end = rounds.back();
    vector<int> ans;
    for (int i = 1; i <= n; ++i)
      if (start <= end) {
        if (start <= i && i <= end)
          ans.push_back(i);
      } else {  // start > end
        if (i >= start || i <= end)
          ans.push_back(i);
      }
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
  public List<Integer> mostVisited(int n, int[] rounds) {
    // 1. If start <= end, [start, end] is the most visited.
    //
    //      s --------- n
    // 1 -------------- n
    // 1 ------ e
    //
    // 2. If start > end, [1, end] and [start, n] are the most visited.
    //
    //             s -- n
    // 1 -------------- n
    // 1 ------ e
    final int start = rounds[0];
    final int end = rounds[rounds.length - 1];
    List<Integer> ans = new ArrayList<>();
    for (int i = 1; i <= n; ++i)
      if (start <= end) {
        if (start <= i && i <= end)
          ans.add(i);
      } else { // start > end
        if (i >= start || i <= end)
          ans.add(i);
      }
    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def mostVisited(self, n: int, rounds: list[int]) -> list[int]:
    # 1. if start <= end, [start, end] is the most visited.
    #
    #      s --------- n
    # 1 -------------- n
    # 1 ------ e
    #
    # 2. if start > end, [1, end] and [start, n] are the most visited.
    #
    #             s -- n
    # 1 -------------- n
    # 1 ------ e
    start = rounds[0]
    end = rounds[-1]
    if start <= end:
      return range(start, end + 1)
    return list(range(1, end + 1)) + list(range(start, n + 1))