-
-
Notifications
You must be signed in to change notification settings - Fork 248
[bus710] Week 02 #746
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
[bus710] Week 02 #746
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
105 changes: 105 additions & 0 deletions
105
construct-binary-tree-from-preorder-and-inorder-traversal/bus710.go
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,105 @@ | ||
package hello | ||
|
||
import ( | ||
"errors" | ||
"log" | ||
) | ||
|
||
type TreeNode struct { | ||
Val int | ||
Left *TreeNode | ||
Right *TreeNode | ||
} | ||
|
||
func buildTree(preorder []int, inorder []int) *TreeNode { | ||
if len(preorder) == 1 { | ||
return &TreeNode{ | ||
Val: preorder[0], | ||
} | ||
} | ||
|
||
center, _ := findCenterWithValue(preorder[0], inorder) | ||
|
||
head := TreeNode{ | ||
Val: inorder[center], | ||
} | ||
|
||
execute(&head, center, inorder) | ||
|
||
return &head | ||
} | ||
|
||
func findCenterWithValue(key int, inorder []int) (int, error) { | ||
for i, n := range inorder { | ||
if n == key { | ||
return i, nil | ||
} | ||
} | ||
return 0, errors.New("not found") | ||
} | ||
|
||
func findCenter(slice []int) int { | ||
c := len(slice) / 2 | ||
return c | ||
} | ||
|
||
func getSplit(center int, inorder []int, currentVal int) ([]int, []int) { | ||
if len(inorder) == 1 { | ||
if inorder[0] == currentVal { | ||
return nil, nil | ||
} | ||
return []int{inorder[0]}, nil | ||
} | ||
if len(inorder) == 2 { | ||
if inorder[0] == currentVal { | ||
return nil, []int{inorder[1]} | ||
} | ||
if inorder[1] == currentVal { | ||
return []int{inorder[0]}, nil | ||
} | ||
return []int{inorder[0]}, []int{inorder[1]} | ||
} | ||
return inorder[:center], inorder[center+1:] | ||
} | ||
|
||
func execute(currentNode *TreeNode, center int, slice []int) { | ||
left, right := getSplit(center, slice, currentNode.Val) | ||
|
||
if len(left) == 1 { | ||
currentNode.Left = &TreeNode{Val: left[0]} | ||
} else if len(left) == 2 { | ||
currentNode.Left = &TreeNode{Val: left[0]} | ||
currentNode.Left.Right = &TreeNode{Val: left[1]} | ||
} else if len(left) > 2 { | ||
lc := findCenter(left) | ||
currentNode.Left = &TreeNode{Val: left[lc]} | ||
|
||
if len(left) > 2 { | ||
execute(currentNode.Left, lc, left) | ||
} | ||
} | ||
|
||
if len(right) == 1 { | ||
currentNode.Right = &TreeNode{Val: right[0]} | ||
} else if len(right) == 2 { | ||
currentNode.Right = &TreeNode{Val: right[0]} | ||
currentNode.Right.Left = &TreeNode{Val: right[1]} | ||
} else if len(right) > 2 { | ||
rc := findCenter(right) | ||
currentNode.Right = &TreeNode{Val: right[rc]} | ||
|
||
if len(right) > 2 { | ||
execute(currentNode.Right, rc, right) | ||
} | ||
} | ||
} | ||
|
||
func print(currentNode *TreeNode) { | ||
log.Println(currentNode.Val) | ||
if currentNode.Left != nil { | ||
print(currentNode.Left) | ||
} | ||
if currentNode.Right != nil { | ||
print(currentNode.Right) | ||
} | ||
} |
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,34 @@ | ||
// T: O(n log n) | ||
// S: O(n) | ||
|
||
pub fn count_bits(n: i32) -> Vec<i32> { | ||
// Prepare a vector. | ||
// The first item can just be 0 | ||
let mut vec = Vec::from([0]); | ||
|
||
// Iterate as many as the given number + 1 | ||
for num in 1..n + 1 { | ||
// Get a binary string from the number (ex: 2 => 10) | ||
let num_str = format!("{num:b}"); | ||
// Count '1' from the given binary string | ||
let cnt = num_str.chars().filter(|c| *c == '1').count(); | ||
// Store the number in the vector | ||
vec.push(cnt as i32); | ||
} | ||
|
||
vec | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn it_works() { | ||
let result = count_bits(2); | ||
assert_eq!(result, Vec::from([0, 1, 1])); | ||
|
||
let result2 = count_bits(5); | ||
assert_eq!(result2, Vec::from([0, 1, 1, 2, 1, 2])); | ||
} | ||
} |
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,56 @@ | ||
// Space complexity: O(2n) - 주어진 한 단어안의 각 문자가 서로 다 다를 경우 생성한 맵들의 최대 길이는 주어진 단어만큼이므로 2n | ||
// Time complexity: O(3n) - 각 맵을 생성하고 추가로 각 아이템을 비교하는 루프가 필요하므로 3n | ||
Comment on lines
+1
to
+2
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. 복잡도 계산에서 상수 계수는 표기하지 않으셔도 괜찮습니다 |
||
|
||
use std::collections::HashMap; | ||
|
||
pub fn is_anagram(s: String, t: String) -> bool { | ||
// Check if the lengh of the 2 words are same. | ||
// Otherwise return false. | ||
let len01 = s.len(); | ||
let len02 = t.len(); | ||
if len01 != len02 { | ||
return false; | ||
} | ||
|
||
// Prepare and fill a new map for s | ||
let mut s_map = HashMap::new(); | ||
for s_char in s.chars() { | ||
let n = s_map.get(&s_char).copied().unwrap_or(0); | ||
s_map.insert(s_char, n + 1); | ||
} | ||
|
||
// Prepare and fill a new map for t | ||
let mut t_map = HashMap::new(); | ||
for t_char in t.chars() { | ||
let n = t_map.get(&t_char).copied().unwrap_or(0); | ||
t_map.insert(t_char, n + 1); | ||
} | ||
|
||
// Iterate over the map s, so compare with the map t | ||
// to see if both have same number for the same character respectively | ||
for (s_char, num) in s_map.iter() { | ||
if t_map.get(s_char).copied().unwrap_or(0) != *num { | ||
return false; | ||
} | ||
} | ||
|
||
true | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn test_good() { | ||
let result = is_anagram("ana".to_owned(), "aan".to_owned()); | ||
assert!(result); | ||
} | ||
|
||
#[test] | ||
fn test_bad() { | ||
let result = is_anagram("aaa".to_owned(), "aan".to_owned()); | ||
assert!(!result); | ||
} | ||
} | ||
|
Oops, something went wrong.
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.
두 테스트 케이스를 한 함수에 넣기 보다는 각각 나누시는 편이 좋을 것 같습니다