리트코드 2225. Find Players With Zero or One Losses

홍성진·2023년 2월 21일
0

리트코드 2225. Find Players With Zero or One Losses

주어진 매치 결과를 가지고, 한 번도 지지 않은 플레이어딱 한 번만 진 플레이어를 추출하는 문제입니다. 플레이어 넘버는 랜덤이기 때문에 전체 플레이어를 상정하고 시작하고 싶은 마음이 듭니다. 하지만 이 때 이긴 사람 목록을 먼저 리스트에 넣고 시작하면 나중에 여기서 진 전적이 있는 플레이어를 제거할 때 찾는 과정에서 시간초과가 납니다.
단순히 array로 풀었지만 dictionary를 활용했다면 좀 더 직관적인 풀이가 됐을 것 같습니다.

import java.util.*;

class Solution {
    public List<List<Integer>> findWinners(int[][] matches) {
        List<List<Integer>> answer = new ArrayList<>();
        ArrayList<Integer> oneLoser = new ArrayList<>();
        ArrayList<Integer> noLoser = new ArrayList<>();
        int[] wins = new int[100001];
        int[] loses = new int[100001];

        for (int[] match : matches) {
            wins[match[0]]++;
            loses[match[1]]++;
        }


        for (int i = 0; i < loses.length; i++) {
        	// wins의 플레이어를 noLoser 리스트에 넣기 전에 이렇게 없애버립니다.
            if (loses[i] != 0) {
                wins[i] = 0;
            }
            if (loses[i] == 1) {
                oneLoser.add(i);
            }
        }

        for (int i = 0; i < wins.length; i++) {
            if (wins[i] != 0) {
                noLoser.add(i);
            }
        }

        Collections.sort(oneLoser);

        answer.add(noLoser);
        answer.add(oneLoser);

        return answer;
    }
}

0개의 댓글