-
-
Notifications
You must be signed in to change notification settings - Fork 361
[okyungjin] WEEK 11 Solutions #2850
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,29 @@ | ||
| ''' | ||
| https://leetcode.com/problems/merge-intervals/description/ | ||
|
|
||
| N: len(intervals) | ||
| Time: O(N logN), 정렬 | ||
| Space: O(N), answer 배열 | ||
| ''' | ||
| class Solution: | ||
| def merge(self, intervals: List[List[int]]) -> List[List[int]]: | ||
| intervals.sort(key=lambda x: x[0]) | ||
|
|
||
| answer = [intervals[0]] | ||
|
|
||
| ''' | ||
| [1,4], [5,8] # case A | ||
| [1,4], [4,7] # case B | ||
| [1,4], [2,8] # case C | ||
| ''' | ||
|
|
||
| for i in range(1, len(intervals)): | ||
| curr_start, curr_end = intervals[i] | ||
| _, last_end = answer[-1] | ||
|
|
||
| if curr_start > last_end: # case A | ||
| answer.append(intervals[i]) | ||
| elif curr_end > last_end: # case C | ||
| answer[-1][1] = curr_end | ||
|
|
||
| return answer |
|
Contributor
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. 🏷️ 알고리즘 패턴 분석missing-number/okyungjin.py'''
https://leetcode.com/problems/missing-number/description/
'''
'''
solution1: 정렬 후 이진탐색
n: len(nums)
Time: O(n log n), sort
Space: O(1)
'''
class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums.sort() # Time: O(n log n)
left = 0
right = len(nums)
while left < right: # Time: O(log n)
mid = (left + right) // 2
if nums[mid] > mid:
right = mid
else:
left = mid + 1
return left
'''
solution2: 0부터 n까지 더한 값에서 배열의 전체 합을 빼기
n: len(nums)
Time: O(n)
Space: O(1)
'''
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
complete_sum = n * (n + 1) // 2
actual_sum = sum(nums) # Time: O(n)
return complete_sum - actual_sum
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(n log n) |
| Space | O(1) |
피드백: 정렬 이후 이진 탐색으로 누락 인덱스를 찾고, 불린 로직으로 누락 수를 도출한다.
개선 제안: 정렬을 피하고 비트 연산 또는 수의 합 방법으로 O(n) 시간과 O(1) 공간 구현이 가능하다.
풀이 2: Solution.missingNumber — Time: O(n) / Space: O(1)
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(1) |
피드백: 간단한 수학적 방법으로 최적의 시간/공간 복잡도를 달성한다.
개선 제안: 덧셈 오버플로우 가능성을 고려해 64비트 정수 사용이 필요할 수 있다. 필요 시 xor 기반 구현도 고려해보자.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| ''' | ||
| https://leetcode.com/problems/missing-number/description/ | ||
| ''' | ||
|
|
||
| ''' | ||
| solution1: 정렬 후 이진탐색 | ||
|
|
||
| n: len(nums) | ||
| Time: O(n log n), sort | ||
| Space: O(1) | ||
| ''' | ||
| class Solution: | ||
| def missingNumber(self, nums: List[int]) -> int: | ||
| nums.sort() # Time: O(n log n) | ||
|
|
||
| left = 0 | ||
| right = len(nums) | ||
|
|
||
| while left < right: # Time: O(log n) | ||
| mid = (left + right) // 2 | ||
|
|
||
| if nums[mid] > mid: | ||
| right = mid | ||
| else: | ||
| left = mid + 1 | ||
|
|
||
| return left | ||
|
|
||
| ''' | ||
| solution2: 0부터 n까지 더한 값에서 배열의 전체 합을 빼기 | ||
|
|
||
| n: len(nums) | ||
| Time: O(n) | ||
| Space: O(1) | ||
| ''' | ||
| class Solution: | ||
| def missingNumber(self, nums: List[int]) -> int: | ||
| n = len(nums) | ||
|
|
||
| complete_sum = n * (n + 1) // 2 | ||
| actual_sum = sum(nums) # Time: O(n) | ||
|
|
||
| return complete_sum - actual_sum | ||
|
Comment on lines
+30
to
+43
Contributor
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. 두 가지 문제 풀이로, 시간복잡도 더 개선된 풀이 보여주신 게 좋네요!👍 |
||
|
Contributor
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. 🏷️ 알고리즘 패턴 분석reorder-list/okyungjin.py"""
https://leetcode.com/problems/reorder-list/
N: number of nodes
Time: O(N)
Space: O(N)
"""
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
nodes = []
curr = head
while curr:
nodes.append(curr)
curr = curr.next
left = 0
right = len(nodes) - 1
while left < right:
nodes[left].next = nodes[right]
left += 1
if left == right:
break
nodes[right].next = nodes[left]
right -= 1
nodes[left].next = None
📊 시간/공간 복잡도 분석
피드백: 정확히 리스트를 순회하며 노드를 모으고 이를 재배치한다. 추가 배열을 사용하므로 시간은 선형, 공간도 선형이다. 개선 제안: 고려해볼 만한 대안: 원래 리스트를 역순으로 반으로 나눈 뒤, 인터리빙으로 연결하는 방식으로 추가 배열 없이 O(1) 공간 구현 가능
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| """ | ||
| https://leetcode.com/problems/reorder-list/ | ||
|
|
||
| N: number of nodes | ||
| Time: O(N) | ||
| Space: O(N) | ||
| """ | ||
| class Solution: | ||
| def reorderList(self, head: Optional[ListNode]) -> None: | ||
| nodes = [] | ||
| curr = head | ||
| while curr: | ||
| nodes.append(curr) | ||
| curr = curr.next | ||
|
|
||
| left = 0 | ||
| right = len(nodes) - 1 | ||
|
|
||
| while left < right: | ||
| nodes[left].next = nodes[right] | ||
| left += 1 | ||
|
|
||
| if left == right: | ||
| break | ||
|
|
||
| nodes[right].next = nodes[left] | ||
| right -= 1 | ||
|
|
||
| nodes[left].next = None |
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.
🏷️ 알고리즘 패턴 분석
merge-intervals/okyungjin.py
📊 시간/공간 복잡도 분석
피드백: 정렬으로 시작점을 기준으로 정렬한 뒤 현재 구간과 마지막 합친 구간을 비교해 필요 시 확장한다.
개선 제안: 현재 구현은 성능에 적절해 보이나 입력 길이가 매우 길 경우 초기 intervals가 빈 배열인 경우를 처리해 주면 안전하다.