-
-
Notifications
You must be signed in to change notification settings - Fork 245
[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 3 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])) |
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.
오 같은 레벨을 이런 식으로 관리할 수도 있군요! 하나 배워 갑니다.