Skip to content

[친환경사과] week 12 #1056

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
Mar 1, 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
34 changes: 34 additions & 0 deletions remove-nth-node-from-end-of-list/EcoFriendlyAppleSu.kt
Copy link
Contributor

Choose a reason for hiding this comment

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

해당 문제는 LinkedList 의 특성을 활용하는 문제로 공간 복잡도를 O(1) 으로 하여 풀이가 가능합니다 :)
어려움이 있으시다면 해답을 확인하시고 이해하시고 넘어가시면 너무 좋을것 같아요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package leetcode_study

/*
* 끝에서 n 번째 노드를 제거하는 문제
* 예외 상황이 발생하는 Case를 나눠 문제 해결
* 시간 복잡도 : O(n)
* -> node list를 순회하며 배열에 담는 과정
* 공간 복잡도 : O(n)
* -> 각 node를 담을 list 공간
* */
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
val tempNodeList = mutableListOf<ListNode>()
var currentHead = head
while (currentHead != null) {
tempNodeList.add(currentHead)
currentHead = currentHead.next
}

val preIndex = tempNodeList.size - n - 1
val postIndex = tempNodeList.size - n + 1

if (preIndex < 0) {
if (tempNodeList.size == 1) {
return null
}
return tempNodeList[postIndex]
} else if (postIndex == tempNodeList.size) {
tempNodeList[preIndex].next = null
return head
} else {
tempNodeList[preIndex].next = tempNodeList[postIndex]
}
return head
}
25 changes: 25 additions & 0 deletions same-tree/EcoFriendlyAppleSu.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package leetcode_study

/**
* 같은 이진 트리 확인 문제
* 재귀를 사용해 문제 해결
*
* 시간 복잡도: O(n)
* -> 모든 노드를 방문하여 비교 진행
* 공간 복잡도: O(n)
* -> 재귀 호출 횟수 n 회
*
* 재귀 문제를 다룰 때 의식적인 연습
* 1. Base Case(기저 조건)를 명확하게 정의
* 2. 기저 조건으로 주어진 문제에 따라서 탈출 조건 정의
* 3. 작은 문제로 나눠 생각하기
* 4. 작은 문제를 결합하여 정답 도출
*/
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {
if (p == null && q == null) return true // 둘 다 null이면 같음
if (p == null || q == null) return false // 한쪽만 null이면 다름
if (p.`val` != q.`val`) return false // 값이 다르면 다름

// 왼쪽 서브트리와 오른쪽 서브트리를 각각 재귀적으로 비교
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}