-
-
Notifications
You must be signed in to change notification settings - Fork 248
[yhkee0404] WEEK 02 solutions #1757
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
Changes from all commits
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,31 @@ | ||
class Solution { | ||
fun threeSum(nums: IntArray): List<List<Int>> { | ||
val ans = mutableListOf<List<Int>>() | ||
nums.sort() | ||
for (i in 0 until nums.size) { | ||
if (i != 0 && nums[i] == nums[i - 1]) { | ||
continue | ||
} | ||
var j = i + 1 | ||
var k = nums.size - 1 | ||
while (j < k) { | ||
if (j != i + 1 && nums[j] == nums[j - 1]) { | ||
j++ | ||
continue | ||
} | ||
val u = nums[i] + nums[j] | ||
while (j < k && u > - nums[k]) { | ||
k-- | ||
} | ||
if (j >= k) { | ||
break | ||
} | ||
if (u == - nums[k]) { | ||
ans.add(listOf(nums[i], nums[j], nums[k])) | ||
} | ||
j++ | ||
} | ||
} | ||
return ans | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
object Solution { | ||
def climbStairs(n: Int): Int = { | ||
val dp = Array.ofDim[Int](n + 1) | ||
dp(0) = 1 | ||
dp(1) = 1 | ||
for (i <- 2 to n) { | ||
dp(i) = dp(i - 1) + dp(i - 2) | ||
} | ||
dp(n) | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
impl Solution { | ||
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> { | ||
let mut ans = vec![1; nums.len()]; | ||
let mut a = 1; | ||
for i in (0..nums.len()).rev() { | ||
ans[i] = a * nums[i]; | ||
a = ans[i]; | ||
} | ||
a = 1; | ||
for i in 0..nums.len() { | ||
ans[i] = a * (if i == nums.len() - 1 {1} else {ans[i + 1]}); | ||
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. 저는 0의 케이스에 대해서 0이 존재하는 개수를 기준으로 3부분으로 나누어서 구별하였는데 이 코드에서는 어떻게 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. 안녕하세요, 저는 0의 예외케이스를 고려하지 않아서 이해가 어려웠는데 그래도 됐던 이유를 @rivkode 님의 코드를 통해 이해하고 여기 설명해 봤습니다: #1758 (comment) 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. 저의 읽기 실력을 더 키워야겠군요 ㅋㅋㅋ 친절한 설명 감사합니다! 전체적으로 코드가 깔끔한 것 같습니다. 앞으로 리뷰가 아니더라도 시간이 되면 종종 @yhkee0404 님의 코드를 살펴봐야겠습니다! 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. Week 1에서 저도 사실 #237 문제 풀 때 |
||
a *= nums[i]; | ||
} | ||
return ans | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
func isAnagram(s string, t string) bool { | ||
sRune := []rune(s) | ||
tRune := []rune(t) | ||
sort.Slice(sRune, func(i, j int) bool { | ||
return sRune[i] < sRune[j] | ||
}) | ||
sort.Slice(tRune, func(i, j int) bool { | ||
return tRune[i] < tRune[j] | ||
}) | ||
return string(sRune) == string(tRune) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
/** | ||
* Definition for a binary tree node. | ||
* 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) | ||
* } | ||
* } | ||
*/ | ||
|
||
function isValidBST(root: TreeNode | null, left = - (1 << 30) * 2, right = - (left + 1)): boolean { | ||
return root === null || root.val >= left && root.val <= right | ||
&& (root.left === null || root.val != (- (1 << 30) * 2) && isValidBST(root.left, left, root.val - 1)) | ||
&& (root.right === null || root.val != - (- (1 << 30) * 2 + 1) && isValidBST(root.right, root.val + 1, 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.
이 부분은 궁금해서 그러는데 이렇게 list로만 add를 해주면 중복이 발생하지 않을까요 ? 만약 제거가 된다면 어디서 처리가 될까요 ?
Uh oh!
There was an error while loading. Please reload this page.
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.
안녕하세요,
continue
를 2군데에서 사용했는데 동일한 원소가 연속적으로 발견되는 경우 Dynamic Programming의 Memoization과 같은 원리로 계산을 건너뛰었어요. 이러한 Tuple의 중복 검사를 위해서는 단순히 Set 자료구조를 사용할 수도 있습니다. 그런데 지금처럼 정렬된 상황에는 Two Pointers를 이용할 수 있어요. 뿐만 아니라 Tuple 내 Index를 탐색하는 순서에 따라 Short-Circuit을 적용하면 추가적인 시간 절약도 기대할 수 있어요. 모든 Tuple 간 중복을 검사하기 위해 중복을 허용하고 생성하는 풀이에 비해 적어도 중복 Tuple 개수 이상의 Tuple 생성 시간 절약 효과를 얻을 수 있습니다.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.
아 설명을 듣고 다시 보니 투포인터를 사용하셨군요! 이제 이해했습니다. 정렬된 상황이라 이전과 같은 숫자에 대해서 continue 로 중복을 제거해주니 중복 처리는 되었고 투포인터로 조건에 맞는 2개의 숫자에 대해서 빠르게 탐색이 되겠네요. 친절한 설명 감사합니다
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.
아! 그리고 short circuit이 이거였군요! 제가 저번 week1 에서 이 용어를 몰라서 헤멨는데 이거였습니다 ㅎㅎㅎ 여기서 알게된게 신기하네요 ㅋㅋㅋ
#1699 (comment)
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.
맞네요! Pruning 등 더 생각 나는 용어를 여기 정리해 봤습니다: #1699 (comment)
예를 들어 저는 순차 탐색의 성질만 이용했으니 Memoization이나 Caching이라고 하기는 어렵겠네요.