-
Notifications
You must be signed in to change notification settings - Fork 126
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
[재호] WEEK 08 Solutions #500
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6e1c133
solve: merge two sorted lists
wogha95 29244bf
solve: longest repeating character replacement
wogha95 a4a6325
solve: clone graph
wogha95 9402dca
solve: longest common subsequence
wogha95 a73f5ca
solve: sum of two integers
wogha95 14c1201
solve: clone graph
wogha95 42f08a6
solve: sum of two integers
wogha95 48be0f5
solve: clone graph
wogha95 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
/** | ||
* TC: O(E) | ||
* graph에 연결된 edge만큼 queue에 추가, 제거하며 순회한다. | ||
* | ||
* SC: O(V + E) | ||
* cloned graph만큼 공간 복잡도 생성해야한다. | ||
* | ||
* V: vertex, E: edge | ||
*/ | ||
|
||
/** | ||
* // Definition for a _Node. | ||
* function _Node(val, neighbors) { | ||
* this.val = val === undefined ? 0 : val; | ||
* this.neighbors = neighbors === undefined ? [] : neighbors; | ||
* }; | ||
*/ | ||
|
||
/** | ||
* @param {_Node} node | ||
* @return {_Node} | ||
*/ | ||
var cloneGraph = function (node) { | ||
if (!node) { | ||
return null; | ||
} | ||
|
||
const memory = new Map(); | ||
const visitedNodeVal = new Set(); | ||
|
||
return bfsClone(node); | ||
|
||
// 1. bfs로 순회하면서 deep clone한 graph의 head를 반환 | ||
function bfsClone(start) { | ||
const queue = [start]; | ||
const clonedHeadNode = new _Node(start.val); | ||
memory.set(start.val, clonedHeadNode); | ||
|
||
while (queue.length > 0) { | ||
const current = queue.shift(); | ||
if (visitedNodeVal.has(current.val)) { | ||
continue; | ||
} | ||
|
||
const clonedCurrentNode = getCloneNode(current.val); | ||
|
||
for (const neighbor of current.neighbors) { | ||
const clonedNeighborNode = getCloneNode(neighbor.val); | ||
clonedCurrentNode.neighbors.push(clonedNeighborNode); | ||
|
||
queue.push(neighbor); | ||
} | ||
|
||
visitedNodeVal.add(current.val); | ||
} | ||
|
||
return clonedHeadNode; | ||
} | ||
|
||
// 2. memory에 val에 해당하는 node 반환 (없을 경우 생성) | ||
function getCloneNode(val) { | ||
if (!memory.has(val)) { | ||
memory.set(val, new _Node(val)); | ||
} | ||
|
||
return memory.get(val); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
/** | ||
* 알고달레 풀이 참고해서 풀었습니다. | ||
* @see https://www.algodale.com/problems/longest-common-subsequence/ | ||
* | ||
* DP + 2차원 배열을 이용한 풀이 | ||
* 행은 text1, 열은 text2에 대응하고 | ||
* index는 text의 처음부터 몇개 문자를 사용할건지 의미합니다. | ||
* 마지막 문자가 동일하다면 dp[index1][index2] = dp[index1 - 1][index2 - 1] + 1 | ||
* 마지막 문자가 다르다면 dp[index1][index2] = Math.max(dp[index1 - 1][index2], dp[index1][index2 - 1]) | ||
* | ||
* TC: O(T1 * T2) | ||
* 2차원 배열을 순회 | ||
* | ||
* SC: O(T1 * T2) | ||
* 2차원 배열 생성 | ||
* | ||
* T1: text1.length, T2: text2.length | ||
*/ | ||
|
||
/** | ||
* @param {string} text1 | ||
* @param {string} text2 | ||
* @return {number} | ||
*/ | ||
var longestCommonSubsequence = function (text1, text2) { | ||
const LENGTH1 = text1.length; | ||
const LENGTH2 = text2.length; | ||
const memory = Array.from({ length: LENGTH1 + 1 }, () => | ||
Array.from({ length: LENGTH2 + 1 }, () => 0) | ||
); | ||
|
||
for (let index1 = 1; index1 <= LENGTH1; index1++) { | ||
for (let index2 = 1; index2 <= LENGTH2; index2++) { | ||
if (text1[index1 - 1] === text2[index2 - 1]) { | ||
memory[index1][index2] = memory[index1 - 1][index2 - 1] + 1; | ||
} else { | ||
memory[index1][index2] = Math.max( | ||
memory[index1 - 1][index2], | ||
memory[index1][index2 - 1] | ||
); | ||
} | ||
} | ||
} | ||
|
||
return memory[LENGTH1][LENGTH2]; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
/** | ||
* 알고달레 풀이 참고 | ||
* @see https://www.algodale.com/problems/longest-repeating-character-replacement/ | ||
* | ||
* TC: O(S) | ||
* right의 순회 + left의 순회 | ||
* (곱이 아닌 더하기인 이유는 right 순회동안 left 순회의 최대 총합이 S이기 때문입니다.) | ||
* | ||
* SC: O(1) | ||
* 최악의 경우 26개의 소문자를 저장하는 memoryMap으로 인해 상수 복잡도를 갖게 됩니다. | ||
* | ||
* S: s.length | ||
*/ | ||
|
||
/** | ||
* @param {string} s | ||
* @param {number} k | ||
* @return {number} | ||
*/ | ||
var characterReplacement = function (s, k) { | ||
// 1. 가장 긴 subString 길이 | ||
let result = 0; | ||
|
||
// 2. left, right 포인터 사이에서 등장한 문자 횟수를 기록한 Map과 최다 등장한 횟수를 기록한 변수 | ||
const memory = new Map(); | ||
let maxCount = 0; | ||
|
||
let left = 0; | ||
let right = 0; | ||
|
||
while (right < s.length) { | ||
// 3. '새로운 문자(s[right])의 갯수 기록'과 '최다 등장한 횟수 갱신' | ||
const newCount = (memory.has(s[right]) ? memory.get(s[right]) : 0) + 1; | ||
memory.set(s[right], newCount); | ||
maxCount = Math.max(maxCount, newCount); | ||
|
||
// 4. k만큼 변경가능한 subString 길이를 맞추기 위해 left 이동 | ||
while (right - left + 1 - maxCount > k) { | ||
const newCount = memory.get(s[left]) - 1; | ||
memory.set(s[left], newCount); | ||
left += 1; | ||
} | ||
|
||
// 5. 가장 긴 subString 길이 갱신, right 이동 | ||
result = Math.max(result, right - left + 1); | ||
right += 1; | ||
} | ||
|
||
return result; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
/** | ||
* TC: O(List1 + List2) | ||
* List1, List2 전체 순회 1번씩 합니다. | ||
* | ||
* SC: O(1) | ||
* List1, List2의 길이와 무관한 고정된 데이터 공간을 사용합니다. (head, pointer 변수들) | ||
* | ||
* List1: list1.length, List2.length; | ||
*/ | ||
|
||
/** | ||
* Definition for singly-linked list. | ||
* function ListNode(val, next) { | ||
* this.val = (val===undefined ? 0 : val) | ||
* this.next = (next===undefined ? null : next) | ||
* } | ||
*/ | ||
/** | ||
* @param {ListNode} list1 | ||
* @param {ListNode} list2 | ||
* @return {ListNode} | ||
*/ | ||
var mergeTwoLists = function (list1, list2) { | ||
// 1. 둘 중 하나의 list가 없는 경우 반대편의 list를 반환 | ||
if (!list1) { | ||
return list2; | ||
} | ||
if (!list2) { | ||
return list1; | ||
} | ||
|
||
// 2. 정답을 반환할 시작점(head)와 list 순회시 필요한 pointer | ||
const head = new ListNode(); | ||
let headPointer = head; | ||
let list1Pointer = list1; | ||
let list2Pointer = list2; | ||
|
||
// 3. 두 list 모두 노드를 가진 경우 | ||
while (list1Pointer && list2Pointer) { | ||
if (list1Pointer.val < list2Pointer.val) { | ||
list1Pointer = connectHeadAndListPointer(list1Pointer); | ||
} else { | ||
list2Pointer = connectHeadAndListPointer(list2Pointer); | ||
} | ||
} | ||
|
||
// 4. 한쪽 list의 남은 노드 연결 | ||
while (list1Pointer) { | ||
list1Pointer = connectHeadAndListPointer(list1Pointer); | ||
} | ||
|
||
while (list2Pointer) { | ||
list2Pointer = connectHeadAndListPointer(list2Pointer); | ||
} | ||
|
||
return head.next; | ||
|
||
// 5. head의 list로 연결 후 다음 노드로 pointer 이동 | ||
function connectHeadAndListPointer(listPointer) { | ||
headPointer.next = listPointer; | ||
listPointer = listPointer.next; | ||
headPointer = headPointer.next; | ||
|
||
return listPointer; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* TC: O(Bit) | ||
* 올림 비트가 0일때까지 while을 실행하게된다. | ||
* | ||
* SC: O(1) | ||
* | ||
* Bit: 2진수 a 와 b 중 비트 길이가 긴 것의 비트 길이 | ||
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. 이 표현은 log(max(a, b)) 정도로 볼 수 있을까요? 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. 앗 비트 길이를 어떻게 표현할 지 고민이었는데 log로 표현할 수 있었군요.! |
||
*/ | ||
|
||
/** | ||
* @param {number} a | ||
* @param {number} b | ||
* @return {number} | ||
*/ | ||
var getSum = function (a, b) { | ||
while (b !== 0) { | ||
const carry = (a & b) << 1; | ||
a = a ^ b; | ||
b = carry; | ||
} | ||
|
||
return a; | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
여기서 모든 경우를 통합 처리하는것도 좋아보입니다.
하지만 62-64라인의 케이스인 경우에는 생성한 노드를 직접 리턴해 주는 것이 메모리 접근을 줄일 수 있지 않을까요?
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.
가독성 측면에서
(노드가 없으면 미리 만들고) 메모리에 있는 노드를 가져온다
로 이해할 수 있도록 작성하였는데 오히려 불필요한 메모리 접근을 늘리는 것을 고려못했습니다!리뷰 감사합니다!