Skip to content
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

[mangodm-web] Week 09 Solutions #524

Merged
merged 2 commits into from
Oct 12, 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
24 changes: 24 additions & 0 deletions find-minimum-in-rotated-sorted-array/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from typing import List


class Solution:
def findMin(self, nums: List[int]) -> int:
"""
- Idea: 회전된 정렬 배열에서 가장 작은 값을 찾기 위해 두 개의 포인터, left, right를 이용한다.
두 개의 포인터는 조건에 따라 배열에서 탐색할 범위를 줄여가는데 활용된다.
- Time Complexity: O(logn). n은 배열의 크기이다.
매번 배열을 절반으로 나눠서 탐색 범위를 줄이기 때문에 O(logn) 시간이 걸린다.
- Space Complexity: O(1). 배열의 크기와 상관없이 left, right, mid 변수만 사용되므로
상수 공간만 차지한다.
"""
left, right = 0, len(nums) - 1

while left < right:
mid = (left + right) // 2

if nums[right] < nums[mid]:
left = mid + 1
else:
right = mid

return nums[left]
33 changes: 33 additions & 0 deletions linked-list-cycle/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import Optional


# Definition for singly-linked list.
class ListNode:
def __init__(self, x: int) -> None:
self.val = x
self.next = None


class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
"""
- Idea: 사이클이 있는 연결 리스트인지 판단하기 위해 두 개의 포인터, slow와 fast를 사용한다.
slow 포인터는 한번에 한 칸씩, fast 포인터는 한번에 두 칸씩 이동한다.
만약 두 포인터가 만나면, 리스트에 사이클이 존재한다고 판단할 수 있다.
fast가 리스트의 끝에 도달한다면 사이클이 없다고 판단한다.
- Time Complexity: O(n). n은 리스트에 포함된 노드의 개수다.
사이클이 없는 경우, fast 포인터는 리스트 끝까지 이동한다.
사이클이 있는 경우, 두 포인터가 만날 때까지 이동하므로 O(n)의 시간이 소요된다.
- Space Complexity: O(1). 연결 리스트의 크기와 상관없이 slow와 fast 변수만 사용되므로
상수 공간만 차지한다.
"""
slow, fast = head, head

while fast and fast.next:
slow = slow.next
fast = fast.next.next

if slow == fast:
return True

return False