<Medium> Get Watched Videos by Your Friends (LeetCode : C#)

이도희·2023년 7월 10일
0

알고리즘 문제 풀이

목록 보기
119/185

https://leetcode.com/problems/get-watched-videos-by-your-friends/

📕 문제 설명

n명의 사람들이 있고 0~n-1의 id를 가진다. Level1은 나의 친구들에 의해 시청된 비디오를, Level2는 나의 친구들과 친구들의 친구들에 시청된 비디오, .. 이런식으로 나아간다. 그래서 Level k는 나를 기준으로 가장 짧은 거리가 k인 사람들에 의해 시청된 비디오를 가리키게 된다. id와 비디오 level이 주어질 때 해당 level에서 비디오가 시청된 빈도수를 기준으로 오름차순으로 정렬한 결과 반환하기 (빈도수 같으면 알파벳 순서대로 정렬하기)

  • Input
    id, level, watchedVideos (i번 사람이 시청한 비디오), friends (i번 사람의 친구)
  • Output
    frequency 기준 오름차순으로 정렬한 결과

예제

풀이

하나씩 해나가면 된다. 우선 레벨이 주어졌으니 해당 레벨에서의 친구들을 찾은 후 친구들이 본 비디오 빈도수를 센다. 그 다음 빈도수 기준 정렬 후 알파벳 순서로 정렬하면 끝!

public class Solution {
    public IList<string> WatchedVideosByFriends(IList<IList<string>> watchedVideos, int[][] friends, int id, int level) {
        int n = watchedVideos.Count;
        bool[] visited = new bool[n];
        visited[id] = true;
        Queue<int> queue = new Queue<int>();
        queue.Enqueue(id);
        
        while (level > 0 && queue.Count > 0) // 현재 레벨의 friend들 담기 위함
        { 
            int size = queue.Count;
            for (int i = 0; i < size; i++) 
            {
                int curr = queue.Dequeue();
                foreach (int friend in friends[curr]) // 현재 level의 친구들
                {
                    if (!visited[friend]) // 방문안했으면 추가 
                    {
                        visited[friend] = true;
                        queue.Enqueue(friend);
                    }
                }
            }
            level--;
        }
        
        Dictionary<string, int> videoCount = new Dictionary<string, int>();
        while (queue.Count > 0) // 현재 레벨 friend 기준 video frequency 확인하기 
        {
            int curr = queue.Dequeue();
            foreach (string video in watchedVideos[curr]) 
            {
                if (!videoCount.ContainsKey(video)) videoCount[video] = 0;       
                videoCount[video]++;
            }
        }
        
        var sortedVideos = videoCount.OrderBy(v => v.Value).ThenBy(v => v.Key); // 빈도수 기준 정렬 후 알파벳 기준 정렬 
        IList<string> result = new List<string>();
        foreach (var kvp in sortedVideos) 
        {
            result.Add(kvp.Key);
        }
        
        return result;
    }
}

결과

profile
하나씩 심어 나가는 개발 농장🥕 (블로그 이전중)

0개의 댓글