Skip to content

[gmlwls96] Week2 #722

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 4 commits into from
Dec 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions 3sum/gmlwls96.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
// 시간 복잡도 : O(n^2)
fun threeSum(nums: IntArray): List<List<Int>> {
val mutableSet = mutableSetOf<List<Int>>() // 결과를 담기 위한 set. 중복을 없애야되서 set으로 만듬.
nums.sort() // 1. nums array를 정렬해주고
for (i in 0..nums.size - 3) {
for (j in i + 1..nums.size - 2) {
for (k in j + 1..nums.lastIndex) {
// 2. nums의 3숫자를 뽑아내기 위해 i, j, k를 순차적으로 조회하면서 합했을때 0이 되는지 체크.
if (nums[i] + nums[j] + nums[k] == 0) {
mutableSet.add(listOf(nums[i], nums[j], nums[k]))
}
}
}
Comment on lines +7 to +14
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for문이 2번 사용되었는데, 투 포인터를 사용해서 풀이해보셔도 재미있을것 같습니다!

}
return mutableSet.toList() // 3. 최종적으로 뽑아낸 결과를 return값에 맞게 set > list로 변환.
}
}
12 changes: 12 additions & 0 deletions climbing-stairs/gmlwls96.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution {
// 시간복잡도 : O(n)
fun climbStairs(n: Int): Int {
val dp = IntArray(n+1)
dp[1] = 1
dp[2] = 2
for(i in 3..n){ // 3부터 n까지 for문.
dp[i] = dp[i-1] + dp[i-2]
}
return dp[n]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
// 시간 : O(n^2)
fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
if (preorder.isEmpty() || inorder.isEmpty()) {
return null
}
val value = preorder[0]
var mid = inorder.indexOf(value)
if (mid < 0) {
mid = 0
}
val leftNode = buildTree(
preorder.slice(1..preorder.lastIndex).toIntArray(),
inorder.slice(0 until mid).toIntArray())
val rightNode = buildTree(
preorder.slice(2..preorder.lastIndex).toIntArray(),
inorder.slice(mid + 1..inorder.lastIndex).toIntArray()
)

return TreeNode(value).apply {
left = leftNode
right = rightNode
}
}
}
8 changes: 8 additions & 0 deletions valid-anagram/gmlwls96.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution {
// 시간 복잡도 : O(nlog(n))
fun isAnagram(s: String, t: String): Boolean {
val sortS = s.toCharArray().apply { sort() } // string을 char array로 변환 후 정렬.
val sortT = t.toCharArray().apply { sort() }
return sortS.concatToString() == sortT.concatToString() // 정렬된 char array를 string으로 만든후 비교.
}
}
Loading