leetcode - most visited sector in a circular track(java)

silver·2021년 6월 30일

level - easy

[문제 내용]
제목 그대로 원형 트랙에서 가장 많이 방문하는 트랙을 반환

[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]

[example 3]

Input: n = 7, rounds = [1,3,5,7]
Output: [1,2,3,4,5,6,7]

[해결 방법]
round 순서대로 방문 개수를 count하는 가장 간단한 방식으로 풀었다.

class Solution {
    public List<Integer> mostVisited(int n, int[] rounds) {
        final HashMap<Integer, Integer> visited = new HashMap<>();
        for(int i=1; i<=n; i++) {
            visited.put(i, 0);
        }
        visited.put(rounds[0], visited.get(rounds[0]) + 1);
        for(int i=0; i<rounds.length-1; i++) {
            int start = rounds[i];
            int end = rounds[i+1];
            if(end <= n && start < end) {
                for(int j=start+1; j<=end; j++) {
                    visited.put(j, visited.get(j)+1);
                }
            } else {
                for(int j=start+1; j<=n; j++) {
                    visited.put(j, visited.get(j)+1);
                }

                for(int j=1; j<=end; j++) {
                    visited.put(j, visited.get(j)+1);
                }
            }
        }

        ArrayList<Integer> keySet = new ArrayList<>(visited.keySet());
        Collections.sort(keySet, new Comparator<Integer>() {
            @Override
            public int compare(Integer integer, Integer t1) {
                return visited.get(t1).compareTo(visited.get(integer));
            }
        });

        ArrayList<Integer> maxList = new ArrayList<>();
        int max = visited.get(keySet.get(0));
        for(int key : keySet) {
            if(max > visited.get(key)) {
                break;
            }

            maxList.add(key);
        }

        Collections.sort(maxList);
        return maxList;
    }
}

0개의 댓글