본문 바로가기
Data Structure & Algorithms/Hasing

[Hashing] Find Players With Zero or One Losses

by 담백로봇 2023. 1. 6.

해쉬에 대해 조금 더 이해도가 생긴듯. 혼자 풀기성공

 

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

Example 2:

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

 

Constraints:

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

class Solution {
public:
    vector<vector<int>> findWinners(vector<vector<int>>& matches) {
        

        vector<int> wlist;
        vector<int> llist;
        vector<vector<int>> result;
        unordered_map<int,int> hashmap;
        
        for( int i=0 ; i < matches.size(); i++){
            for (int ii=0 ; ii< matches[i].size() ; ii++){
                //한번에 어떻게 만들지
                //cout << ii << endl;
                if(ii == 1){ // 진경우의 key에 플러스값 
                    hashmap[matches[i][ii]]++;    
                }
                else{
                    hashmap[matches[i][ii]];
                }
            }
        }

        // 답지 이렇게 표현가능.
        // for (auto& match : matches) {
        //     int winner = match[0], loser = match[1];
        //     if (lossesCount.find(winner) == lossesCount.end()) {
        //         lossesCount[winner] = 0;
        //     }
        //     lossesCount[loser]++;
        // }

         for(auto &[key,val]: hashmap){
            
            if(val == 1){ //lose once
                llist.push_back(key);
            }
            else if(val ==0) { // win always
                wlist.push_back(key);
            }            
        }
        sort(wlist.begin(),wlist.end());
        sort(llist.begin(),llist.end());
        
        result.push_back(wlist);
        result.push_back(llist);

        return result;   
    }
};

댓글