-
-
Notifications
You must be signed in to change notification settings - Fork 195
[SunaDu] Week 14 #1099
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
Merged
Merged
[SunaDu] Week 14 #1099
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6b44ccc
add solution: counting-bits
dusunax ff631d5
add solution: binary-tree-level-order-traversal
dusunax 3d97426
add solution: house-robber-ii
dusunax 707b50c
add solution: meeting-rooms-ii
dusunax f2d9bfc
update solution: update comments on meeting-rooms & meeting-rooms-ii
dusunax 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 hidden or 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,82 @@ | ||
''' | ||
# Leetcode 102. Binary Tree Level Order Traversal | ||
|
||
do level order traversal | ||
|
||
``` | ||
💡 why use BFS?: | ||
BFS is the recommended approach, because it aligns with the problem's concept of processing the binary tree level by level and avoids issues related to recursion depth, making the solution both cleaner and more reliable. | ||
|
||
- DFS doesn't naturally support level-by-level traversal, so we need an extra variable like "dep" (depth). | ||
- BFS is naturally designed for level traversal, making it a better fit for the problem. | ||
- additionally, BFS can avoid potential stack overflow. | ||
``` | ||
|
||
## A. BFS | ||
|
||
### re-structuring the tree into a queue: | ||
- use the queue for traverse the binary tree by level. | ||
|
||
### level traversal: | ||
- pop the leftmost node | ||
- append the node's value to current level's array | ||
- enqueue the left and right children to queue | ||
- can only process nodes at the current level, because of level_size. | ||
|
||
## B. DFS | ||
- travase with a dep parameter => dp(node, dep) | ||
- store the traversal result | ||
''' | ||
class Solution: | ||
''' | ||
A. BFS | ||
TC: O(n) | ||
SC: O(n) | ||
''' | ||
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: | ||
if not root: | ||
return [] | ||
|
||
result = [] # SC: O(n) | ||
queue = deque([root]) # SC: O(n) | ||
|
||
while queue: # TC: O(n) | ||
level_size = len(queue) | ||
level = [] | ||
|
||
for _ in range(level_size): | ||
node = queue.popleft() | ||
level.append(node.val) | ||
|
||
if node.left: | ||
queue.append(node.left) | ||
if node.right: | ||
queue.append(node.right) | ||
|
||
result.append(level) | ||
|
||
return result | ||
|
||
''' | ||
B. DFS | ||
TC: O(n) | ||
SC: O(n) | ||
''' | ||
def levelOrderDP(self, root: Optional[TreeNode]) -> List[List[int]]: | ||
result = [] # SC: O(n) | ||
|
||
def dp(node, dep): | ||
if node is None: | ||
return | ||
|
||
if len(result) <= dep: | ||
result.append([]) | ||
|
||
result[dep].append(node.val) | ||
|
||
dp(node.left, dep + 1) | ||
dp(node.right, dep + 1) | ||
|
||
dp(root, 0) # TC: O(n) call stack | ||
|
||
return result |
This file contains hidden or 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,42 @@ | ||
''' | ||
# 338. Counting Bits | ||
|
||
0부터 n까지의 이진수에서 1의 개수 세기 | ||
|
||
## 풀이A. 브루투포스 | ||
- 전부 계산하기 | ||
|
||
## 풀이B. DP | ||
``` | ||
이진수 = (이진수 >> 1) + (이진수 & 1) | ||
``` | ||
- `i >> 1`: i의 비트를 오른쪽으로 1비트 이동(맨 오른쪽 한 칸 버림), `i // 2`와 같음 | ||
- `i & 1`: `i`의 마지막 비트가 1인지 확인 (1이면 1 추가, 0이면 패스) | ||
- DP 테이블에서 이전 계산(i >> 1) 결과를 가져와서 현재 계산(i & 1) 결과를 더한다. | ||
''' | ||
class Solution: | ||
''' | ||
A. brute force | ||
SC: O(n log n) | ||
TC: O(n) | ||
''' | ||
def countBitsBF(self, n: int) -> List[int]: | ||
result = [] | ||
|
||
for i in range(n + 1): # TC: O(n) | ||
result.append(bin(i).count('1')) # TC: O(log n) | ||
|
||
return result | ||
|
||
''' | ||
B. DP | ||
SC: O(n) | ||
TC: O(n) | ||
''' | ||
def countBits(self, n: int) -> List[int]: | ||
dp = [0] * (n + 1) | ||
|
||
for i in range(1, n + 1): # TC: O(n) | ||
dp[i] = dp[i >> 1] + (i & 1) # TC: O(1) | ||
|
||
return dp |
This file contains hidden or 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,48 @@ | ||
''' | ||
# 213. House Robber II | ||
|
||
house roober 1 + circular array | ||
|
||
## Solution | ||
solve by using two cases: | ||
- robbing from the first house to the last house | ||
- robbing from the second house to the last house | ||
''' | ||
class Solution: | ||
''' | ||
A. pass indices to function | ||
TC: O(n) | ||
SC: O(1) | ||
''' | ||
def rob(self, nums: Lit[int]) -> int: | ||
if len(nums) == 1: | ||
return nums[0] | ||
|
||
def robbing(start, end): | ||
prev, maxAmount = 0, 0 | ||
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. 오 이런식으로 공간 최적화도 할 수 있군요! 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 Solutions 탭을 보면서 정리하는 과정이 도움이 많이 되었어요. 공간 최적화도 이 방법으로 진행했습니다! |
||
|
||
for i in range(start, end): | ||
prev, maxAmount = maxAmount, max(maxAmount, prev + nums[i]) | ||
|
||
return maxAmount | ||
|
||
return max(robbing(0, len(nums) - 1), robbing(1, len(nums))) | ||
|
||
''' | ||
B. pass list to function | ||
TC: O(n) | ||
SC: O(n) (list slicing) | ||
''' | ||
def robWithSlicing(self, nums: List[int]) -> int: | ||
if len(nums) == 1: | ||
return nums[0] | ||
|
||
def robbing(nums): | ||
prev, maxAmount = 0, 0 | ||
|
||
for num in nums: | ||
prev, maxAmount = maxAmount, max(maxAmount, prev + num) | ||
|
||
return maxAmount | ||
|
||
return max(robbing(nums[1:]), robbing(nums[:-1])) |
This file contains hidden or 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,59 @@ | ||
''' | ||
# 253. Meeting Rooms II | ||
|
||
최소 힙 Min Heap을 사용하여 회의 종료 시간을 저장합니다. 최소 힙의 길이는 필요한 회의실 개수입니다. | ||
|
||
## 개념 | ||
``` | ||
💡 최소 힙 Min Heap | ||
- 힙은 완전 이진 트리이다. | ||
- 부모 노드의 값이 자식 노드의 값보다 작다. | ||
- 최소값을 루트에 두기 때문에 최소값을 찾는 시간복잡도가 O(1)이다. | ||
``` | ||
``` | ||
💡 완전 이진 트리 | ||
- 트리의 모든 레벨이 완전히 채워져 있고, 마지막 레벨은 왼쪽부터 채운다. | ||
- 삽입과 삭제는 O(log n)의 시간복잡도를 가진다. | ||
- 삽입은 트리의 마지막 노드에 삽입하고 버블업을 진행한다. | ||
- 삭제는 트리의 루트 노드를 삭제하고, 버블다운을 진행한다. | ||
``` | ||
|
||
## 회의실 재사용 조건 | ||
가장 먼저 끝나는 회의와 다음 회의 시작을 비교하여, 다음 회의 시작이 가장 먼저 끝나는 회의보다 크거나 같다면, 같은 회의실을 사용 가능하다. | ||
|
||
## 풀이 | ||
``` | ||
최소 힙의 길이 = 사용 중인 회의실 개수 = 필요한 회의실 개수 | ||
``` | ||
1. 회의 시작 시간을 기준으로 정렬 | ||
2. 회의 배열을 순회하며 회의 종료 시간을 최소 힙에 저장 | ||
3. 회의실을 재사용할 수 있는 경우, 가장 먼저 끝나는 회의 삭제 후 새 회의 종료 시간 추가(해당 회의실의 종료 시간 업데이트) | ||
4. 최종 사용 중인 회의실 개수를 반환 | ||
|
||
## 시간 & 공간 복잡도 | ||
|
||
### TC is O(n log n) | ||
- 회의 배열 정렬: O(n log n) | ||
- 회의 배열 순회: O(n) | ||
- 최소 힙 삽입 & 삭제: O(log n) | ||
|
||
### SC is O(n) | ||
- 최소 힙: 최악의 경우 O(n) | ||
''' | ||
from heapq import heappush, heappop | ||
|
||
class Solution: | ||
def minMeetingRooms(self, intervals: List[Interval]) -> int: | ||
if not intervals: | ||
return 0 | ||
|
||
intervals.sort(key=lambda x: x.start) | ||
|
||
min_heap = [] | ||
for interval in intervals: | ||
if min_heap and min_heap[0] <= interval.start: | ||
heappop(min_heap) | ||
|
||
heappush(min_heap, interval.end) | ||
|
||
return len(min_heap) |
This file contains hidden or 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
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.
오 같은 레벨을 이런 식으로 관리할 수도 있군요! 하나 배워 갑니다.