- Today
- Total
작심삼일
[LeetCode] 2225 | Find Players With Zero or One Losses 본문
문제 링크: https://leetcode.com/problems/find-players-with-zero-or-one-losses/
문제
You are given an integer array matches where matches[i] = [$winner_i, loser_i$] indicates that the player $winner_i$ defeated player $loser_i$ 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.
조건
- 1 <= matches.length <= $10^5$
- matches[i].length == 2
- 1 <= $winner_i, loser_i$ <= $10^5$
- $winner_i$ != $loser_i$
- All matches[i] are unique.
내 풀이
winners에는 한번도 지지 않은 사람들, losers[0]에는 한번 진 사람, losers[1]에는 두번 이상 진 사람을 저장한다.
matches를 차례로 돌며 각 match=[winner, loser]라 하자.
loser가 winner에 있다면 처음으로 졌기 때문에 winner에서 제거하고 losers[0]에 저장한다.
loser가 losers[0]에 있다면 두번째로 진 것이기 때문에 losers[0]에서 제거하고 losers[1]에 저장한다.
loser가 winners에도 없고 losers[0], losers[1]에 모두 없다면 처음으로 진 것이기 때문에 losers[1]에 저장한다.
winner는 winners(중복 확인), losers[0], losers[1]에 모두 없다면 winner에 저장한다.
리턴할 때는 sorted로 정렬해서 리턴한다.
코드
class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
winners = set()
losers = [set(), set()]
for winner, loser in matches:
if loser in winners:
winners.remove(loser)
losers[0].add(loser)
elif loser in losers[0]:
losers[0].remove(loser)
losers[1].add(loser)
elif loser not in losers[1]:
losers[0].add(loser)
if winner not in winners and winner not in losers[0] and winner not in losers[1]:
winners.add(winner)
return [sorted(winners), sorted(losers[0])]
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 1704 | Determine if String Halves Are Alike | Python (0) | 2022.12.01 |
---|---|
[LeetCode] 1207 | Unique Number of Occurrences | Python (0) | 2022.11.30 |
[LeetCode] 36 | Valid Sudoku | Python (0) | 2022.11.23 |
[LeetCode] 1926 | Nearest Exit from Entrance in Maze | Python (0) | 2022.11.21 |
[LeetCode] 223 | Rectangle Area | Python (0) | 2022.11.17 |