본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1560. Most Visited Sector in a Circular Track

반응형

https://leetcode.com/problems/most-visited-sector-in-a-circular-track/description/

순환을 구현한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 vector visited, sector별 방문자를 저장할 vector visitedPerSector를 선언 후 round 0의 시작 sector를 방문처리합니다.

📔 풀이과정

1. 각 round별 loop를 수행합니다.2. start는 round[i-1], end는 round[i]가 되며 내부에서 while loop를 수행합니다.   2-1. end가 아닐때까지 start를 증가시켜줍니다.   2-2. 이 때 한 바퀴 돌았다는 것을 처리하기 위해 나머지 연산을 사용해 그 결과에 1을 더하는 방식으로 다음 방문 sector를 구해 start에 저장합니다. overflow 방지를 위해 start - 1값을 visitedPerSector에 저장합니다.3. visitedPerSector의 원소중 최댓값을 찾아 maxVisited에 저장해줍니다.4. visitedPerSector를 순회하며 maxVisited값을 가진 구역을 visited에 push_back해줍니다. 이 때 overflow처리를 했으므로

📔 정답 출력 | 반환

visited를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> mostVisited(int n, vector<int>& rounds) {
        vector <int> visited;
        vector <int> visitedPerSector(n, 0);
        visitedPerSector[rounds[0] - 1]++;
        for(int i = 1; i < rounds.size(); i++) {
            int start = rounds[i - 1];
            int end = rounds[i];
            while(start != end) {
                start = start % n + 1;
                visitedPerSector[start - 1]++;
            }
        }
        int maxVisited = 0;
        for(auto v : visitedPerSector) {
            maxVisited = max(maxVisited, v);
        }
        for(int i = 0; i < n; i++) {
            if(visitedPerSector[i] == maxVisited) {
                visited.push_back(i+1);
            }
        }
        return visited;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.