본문 바로가기
LeetCode

2225. Find Players With Zero or One Losses

by 초코맛젤리 2022. 11. 28.

2225. Find Players With Zero or One Losses

Medium


You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.

Return a list answer of size 2 where:

  • answer[0] is a list of all players that have not lost any matches.
  • answer[1] is a list of all players that have lost exactly one match.

The values in the two lists should be returned in increasing order.

Note:

  • You should only consider the players that have played at least one match.
  • The testcases will be generated such that no two matches will have the same outcome.

 

Example 1:

Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
Output: [[1,2,10],[4,5,7,8]]
Explanation:
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].

 

Constraints:

  • 1 <= matches.length <= 105
  • matches[i].length == 2
  • 1 <= winneri, loseri <= 105
  • winneri != loseri
  • All matches[i] are unique.

이 문제는 한번도 진적이 없는 사람들과 딱 한 번만 진 사람들을 찾는 문제입니다.

map을 이용해서 간단하게 풀수 있습니다.

처음에는 winner, loser 둘 다 따로 map을 만들어서 풀었지만

그것보다 둘이 합쳐서 관리하는 게 더 좋다고 생각해서 리팩터링 한 문제입니다.

조건에 맞는 사람들을 찾기 위해 이긴사람은 값을 0 

진 사람은 계속해서 1을 더한값을 저장해주었습니다. 

 

/**
 * @param {number[][]} matches
 * @return {number[][]}
 */
var findWinners = function(matches) {
    const total = new Map()
    
    for(const match of matches){
        const [win, lose] = match
        
        total.set(win, (total.get(win)||0))
        total.set(lose, (total.get(lose)||0)+1)
    }
    
    const winner = [] , loser = []
    
    for(const [key, value] of total){
        if(value === 0) winner.push(key)
        if(value === 1) loser.push(key)
    }
    
    winner.sort((a,b)=>a-b)
    loser.sort((a,b)=>a-b)
    
    return [winner, loser]
};

'LeetCode' 카테고리의 다른 글

209. Minimum Size Subarray Sum  (0) 2022.12.28
346. Moving Average from Data Stream  (0) 2022.12.26
967. Numbers With Same Consecutive Differences  (0) 2022.11.26
49. Group Anagrams  (0) 2022.11.26
216. Combination Sum III  (0) 2022.11.24