LeetCode 1560: Most Visited Sector in a Circular Track

ArraySimulation

Problem Description

Explanation:

To solve this problem, we need to simulate the marathon rounds and count the number of visits to each sector. We can achieve this by iterating over the rounds array and incrementing a counter for each sector visited during the marathon. Finally, we find the sectors with the maximum number of visits.

  • Algorithm:

    1. Initialize an array sectorCount of size n+1 to store the count of visits for each sector.
    2. Iterate over the rounds array and increment the count for each sector visited in the current round.
    3. Find the maximum count among all sectors.
    4. Iterate over the sectorCount array and add sectors with the maximum count to the result list.
  • Time Complexity: O(m) where m is the number of rounds.

  • Space Complexity: O(n) where n is the number of sectors.

Solutions

class Solution {
    public List<Integer> mostVisited(int n, int[] rounds) {
        int[] sectorCount = new int[n+1];
        int m = rounds.length;
        
        for (int i = 1; i < m; i++) {
            int start = rounds[i - 1];
            int end = rounds[i];
            while (start != end) {
                sectorCount[start]++;
                start = (start % n) + 1;
            }
        }
        
        int maxCount = 0;
        for (int count : sectorCount) {
            maxCount = Math.max(maxCount, count);
        }
        
        List<Integer> result = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            if (sectorCount[i] == maxCount) {
                result.add(i);
            }
        }
        
        return result;
    }
}

Loading editor...