넘치게 채우기

[LeetCode] 2225. Find Players With Zero or One Losses 본문

PS/LeetCode

[LeetCode] 2225. Find Players With Zero or One Losses

riveroverflow 2024. 1. 15. 12:08
728x90
반응형

https://leetcode.com/problems/find-players-with-zero-or-one-losses/description/

 

Find Players With Zero or One Losses - LeetCode

Can you solve this real interview question? Find Players With Zero or One Losses - 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

leetcode.com

leetcode - 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.

 

당신은 정수 배열 matches[i] = [winneri, loseri]를 받는다. i번째 매치의 승자와 패자이다.

 

다음의 조건을 만족하는 크기가 2인 배열을 반환하라:

  • answer[0]은 한 번도 진 적 없는 선수들의 리스트이다.
  • answer[1]은 단 한번만 진 선수들의 리스트이다.

두 리스트의 값은 오름차순으로 반환되어야 한다.

 

주의:

각 플레이어들이 적어도 한 번은 경기를 합니다.

테스트케이스는 같은 결과를 가진 매치를 중복해서 가지지 않습니다.

 

 

풀이

플레이어별로 패배한 숫자를 측정하기 위해 map을 생성하여 패배 수를 기록합니다.(선수번호 - 패배횟수)

각 match들을 읽어나가면서 경기를 해석합니다.

match[1]의 선수의 패배 수를 1 증가시킵니다.

만약 match[0]의 선수가 처음 등장했다면, 0으로 초기화시킵니다.

 

경기 분석을 끝내고, map의 각 요소들에 대해 해석합니다.

패배 수가 0이면 answer[0]에 선수번호를 넣고, 1이면 answer[1]에 선수번호를 넣습니다.

answer[0]과 answer[1]을 각각 정렬시킵니다.

 

answer를 반환합니다.

 

 

코드

C++

static const int __ = [](){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    return 0;
}();

class Solution {
public:
    vector<vector<int>> findWinners(vector<vector<int>>& matches) {
        vector<vector<int>> answer(2, vector<int>());
        unordered_map<int, int> mp;

        for(const auto &match : matches) {
            if(!mp[match[0]]) mp[match[0]] = 0;
            mp[match[1]]++;
        }

        for(const auto &m : mp) {
            if(m.second == 1) {
                answer[1].emplace_back(m.first);
            } else if(m.second == 0) {
                answer[0].emplace_back(m.first);
            }
        }

        sort(answer[0].begin(), answer[0].end());
        sort(answer[1].begin(), answer[1].end());

        return answer;
    }
};
728x90
반응형