Skip to content

[친환경사과] week 10 #1018

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 2 commits into from
Feb 16, 2025
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
36 changes: 36 additions & 0 deletions invert-binary-tree/EcoFriendlyAppleSu.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package leetcode_study

/*
* binary tree 좌우 번경 문제
* 재귀를 통해 문제 해결
* 시간 복잡도: O(n)
* -> n개의 노드를 한 번씩 방문
* 공간 복잡도: O(n) 혹은 O(log n)
* -> 재귀 사용 시 스택에 쌓임
* -> 균형잡힌 binary tree의 경우 O(log n)의 공간이 필요하고 그렇지 않은 경우(최악의 경우) O(n)의 공간 복잡도 요구
* */
fun invertTree(root: TreeNode?): TreeNode? {
recursiveNode(root)
return root
}

fun recursiveNode(parentNode: TreeNode?) {
if (parentNode == null) return

swapNode(parentNode) // 현재 노드의 left와 right를 교환
recursiveNode(parentNode.left) // 왼쪽 서브트리 탐색
recursiveNode(parentNode.right) // 오른쪽 서브트리 탐색
}

fun swapNode(parentNode: TreeNode?) {
Copy link
Contributor

Choose a reason for hiding this comment

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

개인적으로 swapNode를 따로 함수로 빼기보다는 recursiveNode에 포함시키면 코드가 간결해질 것 같다는 의견입니다!

if (parentNode == null) return

val temp = parentNode.left
parentNode.left = parentNode.right
parentNode.right = temp
}

class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
41 changes: 41 additions & 0 deletions search-in-rotated-sorted-array/EcoFriendlyAppleSu.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package leetcode_study

/*
* 회전된(shifted) 정렬 배열에서 O(log n) 시간 복잡도로 target 값의 index를 찾는 문제
*
* 이진 탐색 (Binary Search) 사용
* 각 반복마다 중간 값(mid)을 기준으로 배열을 절반씩 줄이며 탐색
* 배열의 한쪽 절반은 항상 정렬되어 있으므로, 정렬된 구간을 기준으로 탐색 방향 결정
*
* 시간 복잡도: O(log n)
* -> 매번 탐색 공간을 절반으로 줄이므로 O(log n)
* 공간 복잡도: O(1)
* -> 추가적인 공간을 사용하지 않고 변수만 사용하므로 O(1)
* */
fun search(nums: IntArray, target: Int): Int {
var start = 0
var end = nums.size - 1

while (start <= end) {
val mid = start + (end - start) / 2
if (nums[mid] == target) return mid

// 왼쪽 부분이 정렬된 경우
if (nums[start] <= nums[mid]) {
if (nums[start] <= target && target < nums[mid]) {
end = mid - 1 // 왼쪽에서 탐색
} else {
start = mid + 1 // 오른쪽에서 탐색 -> 다음 루프에서 정렬되지 않은 오른쪽 탐색
}
}
// 오른쪽 부분이 정렬된 경우
else {
if (nums[mid] < target && target <= nums[end]) {
start = mid + 1 // 오른쪽에서 탐색
} else {
end = mid - 1 // 왼쪽에서 탐색 -> 다음 루프에서 정렬되지 않은 왼쪽 탐색
}
}
}
return -1
}