Leetcode 1560. Most Visited Sector in a Circular Track Sure! Let’s tackle the problem step by step.
You are given an integer n and an integer array rounds. The track consists of n sectors numbered from 1 to n. A marathoner will be running on the track starting at sector rounds[0] and will run in the direction specified by the subsequent elements in the array rounds.
Return an array of the most visited sectors sorted in ascending order.
rounds array be non-decreasing?The strategy to solve this problem is as follows:
rounds[0].Here is how you can implement this strategy in C++:
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <iostream>
std::vector<int> mostVisited(int n, std::vector<int>& rounds) {
// Create a frequency map to count visits to each sector
std::vector<int> visitCount(n + 1, 0);
int start = rounds[0];
visitCount[start]++;
for (int i = 1; i < rounds.size(); ++i) {
int current = start;
int next = rounds[i];
if (next > current) {
for (int sector = current + 1; sector <= next; ++sector) {
visitCount[sector]++;
}
} else if (next < current) {
for (int sector = current + 1; sector <= n; ++sector) {
visitCount[sector]++;
}
for (int sector = 1; sector <= next; ++sector) {
visitCount[sector]++;
}
}
start = next;
}
// Find the maximum visit count
int maxVisit = *std::max_element(visitCount.begin(), visitCount.end());
// Collect all sectors with the maximum visit count
std::vector<int> result;
for (int sector = 1; sector <= n; ++sector) {
if (visitCount[sector] == maxVisit) {
result.push_back(sector);
}
}
return result;
}
int main() {
int n = 4;
std::vector<int> rounds = {1, 3, 1, 2};
std::vector<int> result = mostVisited(n, rounds);
for (int sector : result) {
std::cout << sector << " ";
}
std::cout << std::endl; // Output: 1 2
return 0;
}
visitCount vector.rounds array. However, there could be an internal loop that runs in worst case O(n) for each segment.
Thus, the overall complexity is O(n * m), which is efficient given that n and m are typically not extraordinarily large based on problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?