Given an integer n
and an integer array rounds
. We have a circular track that 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).
Example 1:
Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
Example 2:
Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
Output: [2]
Approach
C++
#include <bits/stdc++.h>using namespace std;vector<int> mostVisited(int n, vector<int> &rounds){vector<int> mostVisited;int start = rounds[0];int end = rounds.back();if (start <= end){for (int i = start; i <= end; ++i)mostVisited.push_back(i);}else{for (int i = 1; i <= n; ++i){if (i >= start || i <= end)mostVisited.push_back(i);}}return mostVisited;}int main(){int n = 4;vector<int> rounds = {1, 3, 1, 2};vector<int> res = mostVisited(n, rounds);cout << "[";for (int i = 0; i < res.size(); i++){cout << res[i];if (i != res.size() - 1)cout << ",";}cout << "]";return 0;}
No comments:
Post a Comment