Repository navigation
[novacat25] WEEK 04 Solutions #2965
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
9983c74
c13c94f
b05f136
507dc55
86bd772
72c6ea0
c745630
7b633e1
028f405
286b964
1636c94
8a18e3b
43eb710
db6faa9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /* | ||
| 시간 복잡도: O(amount * n) | ||
| 공간 복잡도: O(amount) | ||
| 풀이 기법: Dynamic Programming을 이용한다. Greedy Algorithm의 경우, [1,3,4]와 6의 반례에서는 실패하기에 remain = amount - coin 기준으로 Min 값을 반환할 수 있도록 하는 DP를 이용하는 것이 이상적. | ||
| */ | ||
| /* 풀이 1: Bottom-up */ | ||
| const coinChange = (coins: number[], amount: number): number => { | ||
| const INVALID_ANSWER_CONDITION = Infinity | ||
|
|
||
| const dp: number[] = new Array(amount + 1).fill(INVALID_ANSWER_CONDITION) //Invalid Value: Infinity | ||
| dp[0] = 0 | ||
|
|
||
| for (let i = 1; i <= amount; i++) { | ||
| for (const coin of coins) { | ||
| if (coin <= i) { | ||
| dp[i] = Math.min(dp[i], dp[i - coin] + 1) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return dp[amount] > amount ? -1 : dp[amount] | ||
| } | ||
|
|
||
| /* 풀이 2: Top-Down */ | ||
| // // 값을 찾지 못한 경우 -Infinity, 조건 상 성립할 수 없는 경우 Infinity. 그로 인해 답이 없다면 -1을 반환함. | ||
| // const NOT_SEARCHED = -Infinity | ||
| // const INVALID_ANSWER_CONDITION = Infinity | ||
| // const INVALID_ANSWER = -1 | ||
|
|
||
| // const solveCoin = (memo: number[], coins: number[], remaining: number): number => { | ||
| // if (remaining === 0) return 0 | ||
| // if (remaining < 0) return INVALID_ANSWER_CONDITION | ||
| // if (memo[remaining] !== NOT_SEARCHED) return memo[remaining] | ||
|
|
||
| // let minCoins = INVALID_ANSWER_CONDITION | ||
|
|
||
| // for (const coin of coins) { | ||
| // const sub = solveCoin(memo, coins, remaining - coin) | ||
| // minCoins = Math.min(minCoins, sub + 1) | ||
| // } | ||
| // memo[remaining] = minCoins | ||
| // return minCoins | ||
| // } | ||
|
|
||
| // const coinChange = (coins: number[], amount: number): number => { | ||
| // const memo: number[] = new Array(amount + 1).fill(NOT_SEARCHED) | ||
| // const result = solveCoin(memo, coins, amount) | ||
| // return result === INVALID_ANSWER_CONDITION ? INVALID_ANSWER : result | ||
| // } |
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 시간 복잡도가 O(log n)으로 제한되어 있어서, mid를 보고 최솟값이 속한 구간이 left인지 right인지 판단해 절반씩 줄여 나가는 방식이군요! |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /* | ||
| 시간 복잡도(TC): O(log n) | ||
| 공간 복잡도(SC): O(1) | ||
| 풀이: Binary Search를 이용하여 O(log n) 시간 이내에 답을 구한다. | ||
| 조건: | ||
| - 모든 Item을 Search하는 Linear Search는 시간 복잡도가 O(n)이므로 문제 요구사항을 위배한다. | ||
| - 모든 item 값은 unique하다. => 중복된 값이 있는 경우라면 index 연산이 애매해지겠으나, 모든 값이 유일하다면 Binary Search를 일관되게 보장할 수 있다. | ||
|
|
||
| Binary Search를 적용할 수 있는 조건 | ||
| - 반드시 해당 배열이 정렬되어 있어야 한다. | ||
| - Input Array의 경우에는 완전히 정렬되어 있지는 않으나, 'n번 rotate 후 원래의 배열로 돌아간다 = 2개의 Sort된 배열이 합쳐져 있다'는 조건으로 간주되어 Binary Search 적용이 가능하다. | ||
| - 분기는 다음과 같다. | ||
| - nums[mid] > nums[right]인 경우 => left ~ mid 구간까지는 더 큰 값이 들어 있는 sorted Array임이 자명하므로, mid까지 포함하지 않고 left = mid + 1로 배제하여 탐색 범위를 크게 줄인다. | ||
| - nums[mid] <= nums[right]인 경우 => mid ~ right 구간은 sorted & ascending 상태가 보장된다. minimum value는 mid가 될 수도 있으므로 right 값에 mid를 덮어씌운다. | ||
| */ | ||
|
|
||
| const findMin = (nums: number[]): number => { | ||
| let left = 0 | ||
| let right = nums.length - 1 | ||
|
|
||
| if (nums[left] < nums[right]) return nums[left] | ||
|
|
||
| while (left < right) { | ||
| const mid = Math.floor(left + (right - left) / 2) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (left + right) / 2 대신 left + (right - left) / 2로 쓰신 이유는 overflow 방지 때문인가요?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 일부 프로그래밍 언어에서는 (left + right) / 2 연산으로 인해 오버플로의 리스크가 있을 수 있어
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 타입스크립트에선 64비트 부동소수점 자료형이라 이번 경우엔 필요는 없는데요. 다만, 매우 큰 정수 범위를 대상으로 하는 경우 이 방식으로 정밀도 손실을 방지할 수 있을 거 같습니다. |
||
| if (nums[mid] > nums[right]) { | ||
| left = mid + 1 | ||
| } else { | ||
|
Comment on lines
+25
to
+27
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 정렬되있는 경우엔 즉시 반환할 수 있어서 최적화 해보셔도 좋을 거 같습니다.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 힌트 감사합니다!
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 좀더 최적화 하는 느낌이라 해보시면 재밌으실 거 같아요!
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @parkhojeong
따라서 nums[left] < nums[right]로 검사하면 |
||
| right = mid | ||
| } | ||
| } | ||
|
|
||
| return nums[left] | ||
| } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 수평을 모두 탐색한 뒤 다음 층으로 넘어가는 BFS 풀이까지 1차 DFS 풀이와 대조해서 보여 주셔서 인상 깊습니다 ㅎㅎ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| /* | ||
| [2차 풀이] | ||
| 시간 복잡도(TC): O(n) | ||
| 공간 복잡도(SC): O(n) | ||
| 풀이: BFS와 Queue를 이용해, 수평 방향으로 우선하여 탐색한다. Queue는 발견했지만 탐색되지 않은 노드열이다. | ||
| */ | ||
| class TreeNode { | ||
| val: number | ||
| left: TreeNode | null | ||
| right: TreeNode | null | ||
| constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { | ||
| this.val = val === undefined ? 0 : val | ||
| this.left = left === undefined ? null : left | ||
| this.right = right === undefined ? null : right | ||
| } | ||
| } | ||
|
|
||
| const isQueueEmpty = (queue: TreeNode[]) => queue.length === 0 | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. while (nodeQueue.length) 대신 큐가 비어있다는 것을 확인하기 위해 함수를 따로 만드신 것이군요!
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 네, 조금 더 가독성에 사치를 부려 봤어요! |
||
|
|
||
| const maxDepth = (root: TreeNode | null): number => { | ||
| const DEFAULT_VALUE = 0 | ||
| if (!root) return DEFAULT_VALUE | ||
|
|
||
| const nodeQueue = [root] | ||
| let depth = 0 | ||
|
|
||
| while (!isQueueEmpty(nodeQueue)) { | ||
| const levelSize = nodeQueue.length | ||
|
|
||
| for (let i = 0; i < levelSize; i++) { | ||
| const currentNode = nodeQueue.shift() | ||
|
Comment on lines
+30
to
+31
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. child node가 계속 push되니까 levelSize를 미리 const로 고정해 두고, 그 길이만큼 꺼내서 한 층을 처리한 뒤 depth를 추가하는 원리군요
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 네, 해당 Queue의 levelSize만큼만 shift로 빼고, 나머지는 다음 while 분기에 넘기도록 했습니다.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 설명 감사합니다! levelSize만큼만 꺼내고 나머지는 다음 층으로 넘기는 구조 기억하도록 하겠습니다 |
||
|
|
||
| if (currentNode?.left) { | ||
| nodeQueue.push(currentNode.left) | ||
| } | ||
|
|
||
| if (currentNode?.right) { | ||
| nodeQueue.push(currentNode.right) | ||
| } | ||
| } | ||
|
|
||
| depth++ | ||
| } | ||
|
Comment on lines
+27
to
+43
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 같은 siblings끼리 확인할 때마다 depth를 늘려서 구하는 방식 좋은 것 같습니다! |
||
|
|
||
| return depth | ||
| } | ||
|
|
||
| /* | ||
| [1차 풀이] | ||
| 시간 복잡도(TC): O(n) | ||
| 공간 복잡도(SC): O(h) - h는 Tree의 높이 | ||
| 풀이: 재귀 코드를 활용하여, root 기준으로 left/right를 전개하여 풀어나간다. root가 존재하지 않는 기본값은 0으로, Math.max(left, right) 후 추가로 높이 보정치인 1을 더한다. | ||
| */ | ||
| // const maxDepth = (root: TreeNode | null): number => { | ||
| // const DEFAULT_VALUE = 0 | ||
|
|
||
| // if (!root) return DEFAULT_VALUE | ||
| // let leftHeight = maxDepth(root.left) | ||
| // let rightHeight = maxDepth(root.right) | ||
|
|
||
| // return Math.max(leftHeight, rightHeight) + 1 | ||
| // } | ||
|
Comment on lines
+49
to
+62
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1번째 풀이는 재귀dfs로 푸셨네요! |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| /* | ||
| 핵심 팁 | ||
| 문제에서 주어지는 list1 = [1,2,4] 및 list2 = [1,3,4]는 그대로 배열을 쓰는 것이 아니다!! (constructor 부분 주목) | ||
| const list1 = new ListNode(1, new ListNode(2, new ListNode(4))) // [1] -> [2] -> [4] -> null | ||
| const list2 = new ListNode(1, new ListNode(3, new ListNode(4))) // [1] -> [3] -> [4] -> null | ||
|
Comment on lines
+2
to
+5
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 팁까지 적어 주셔서 감사합니다 :)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 아, 이 부분은 LeetCode가 input sample을 줄 때 Online TS Compiler에서 '이거 어떻게 처리해야 하나?' 하고 막혀있었던 걸 조금 더 확실히 하기 위해 쓴 거에요! |
||
| */ | ||
|
|
||
| class ListNode { | ||
| val: number | ||
| next: ListNode | null | ||
| constructor(val?: number, next?: ListNode | null) { | ||
| this.val = val === undefined ? 0 : val | ||
| this.next = next === undefined ? null : next | ||
| } | ||
| } | ||
|
|
||
| /* | ||
| [2차 풀이] | ||
| 시간 복잡도: O(n + m) | ||
| 공간 복잡도: O(n + m) -> O(1) | ||
| 풀이 기법: Iterative(Dummy Node)로 문제 분해 + Call Stack 기법 대신 객체 참조(Reference)와 포인터 이동을 통해 공간 복잡도를 절약함. | ||
| 풀이 원리: | ||
| (1) tail.next = list1 or list2로 dummy의 객체 속성을 변경시킨다. | ||
| (2) list1 = list1.next or list2 = list2.next로 입력 리스트의 참조를 이동한다. | ||
| (3) tail = tail.next로 결과 리스트의 참조를 이동한다. | ||
|
|
||
| 이 과정에서 dummy는 시작 위치를 그대로 저장하고 있는다. | ||
| */ | ||
|
|
||
| const mergeTwoLists = ( | ||
| list1: ListNode | null, | ||
| list2: ListNode | null, | ||
| ): ListNode | null => { | ||
| const dummyNode = new ListNode(0) | ||
| let tail = dummyNode | ||
|
|
||
| while (list1 !== null && list2 !== null) { | ||
| if (list1.val <= list2.val) { | ||
| tail.next = list1 | ||
| list1 = list1.next | ||
| } else { | ||
| tail.next = list2 | ||
| list2 = list2.next | ||
| } | ||
| tail = tail.next | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이게 Reference 기능을 통해 |
||
| } | ||
|
|
||
| tail.next = list1 ?? list2 | ||
|
|
||
| return dummyNode.next | ||
| } | ||
|
|
||
| /* | ||
| [1차 풀이] | ||
| 시간 복잡도: O(n + m) | ||
| 공간 복잡도: O(n + m) | ||
| 풀이 기법: Recursion | ||
|
|
||
| Self Feedback: | ||
| - 최초 풀이에서는 Linked List의 구조 및 재귀적 문제 분해에 대한 이해 부족으로 아이디어를 독립적으로 도출하지 못했다. | ||
| - 외부 해설에서 원리를 참고한 뒤 직접 구현하여 정답에 도달했다. | ||
| - 이후 ListNode의 constructor와 객체 참조를 확인하며 자료구조에 대한 이해를 보완했다. | ||
| - 손풀이를 통해 재귀 호출의 인자 변화, Base case 및 반환 과정까지 추적했다. | ||
| - 추후 해설 없이 재귀 풀이를 재구현할 필요가 있다. | ||
| */ | ||
|
|
||
| // const mergeTwoLists = ( | ||
| // list1: ListNode | null, | ||
| // list2: ListNode | null, | ||
| // ): ListNode | null => { | ||
| // // Base cases | ||
| // if (!list1) return list2 | ||
| // if (!list2) return list1 | ||
|
|
||
| // if (list1.val <= list2.val) { | ||
| // list1.next = mergeTwoLists(list1.next, list2) | ||
| // return list1 | ||
| // } else { | ||
| // list2.next = mergeTwoLists(list1, list2.next) | ||
| // return list2 | ||
| // } | ||
| // } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 left, right를 사용해서 이진탐색으로 구현한 풀이 잘 봤습니다!
저는 매번 새로운 배열을 만드는 방식으로 진행했는데 풀이대로 하면 공간 복잡도를 줄일 수 있겠네요.
이진 탐색의 조건을 주석으로 적어주신 것도 감사합니다! 공부가 됐습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
문제 조건에서 뜻을 도출하는 것도 중요한 거 같더라고요!
거기서 꽤 많은 힌트가 녹아 있고, 특히 LeetCode는 이 부분을 되게 꼼꼼하게 잡아주는 것 같습니다.
(DP에서 일반 재귀를 쓰면 TLE가 나도록 설계를 했다던지)