일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 영어원서읽기
- 잡생각
- 스탭퍼
- 파비최
- 링피트
- 매일
- Writing
- 10분
- 운동
- FIT XR
- 사이드
- 30분
- English
- 만화도
- 쓰릴오브파이트
- 뭐든
- 미드시청
- 3줄정리
- 개발자
- leetcode
- 영어공부
- 리얼 클래스
- realclass
- 읽기
- Problem Solving
- 월간
- Daily Challenge
- 괜찮음
- 프로젝트
- 화상영어
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.11.11 Today's Challenge 본문
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/
Restore the Array From Adjacent Pairs - LeetCode
Can you solve this real interview question? Restore the Array From Adjacent Pairs - There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are give
leetcode.com
DFS로 푸는 문제.
인접 리스트를 만들어서 풀면 될 것 같다는 생각이 어렴풋이 들긴 했는데 결국 못품 ㅠㅠ
그래도 로컬에서 디버깅 하면서 어떤 개념으로 돌아가는지 눈으로 한번 더 확인함.
사실 모르면 안되는 부분일 수 있긴한데.. 뭐 다음에는 해설 안보고 인접 리스트까지 만드는 것만 해도 충분 할 듯
class Solution:
def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
gr = defaultdict(list)
for x, y in adjacentPairs:
gr[x].append(y)
gr[y].append(x)
root = None
for n in gr:
if len(gr[n]) == 1:
root = n
break
def dfs(node, prev, ans):
ans.append(node)
for nei in gr[node]:
if nei != prev:
dfs(nei, node, ans)
ans = []
dfs(root, None, ans)
return ans
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.11.13 Today's Challenge (0) | 2023.11.13 |
---|---|
2023.11.12 Today's Challenge (0) | 2023.11.12 |
2023.11.10 Today's Challenge (0) | 2023.11.10 |
2023.11.09 Today's Challenge (0) | 2023.11.09 |
2023.11.08 Today's Challenge (0) | 2023.11.08 |
Comments