-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solve: linkedListCycle, findMinimumInRotatedSortedArray
- Loading branch information
1 parent
f2b9477
commit fb9f931
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Time Complexity: O(log n) - using binary search, so cut the search space in half each time. | ||
# Space Complexity: O(1) - only use a few variables (low, high, mid), no extra space. | ||
|
||
class Solution: | ||
def findMin(self, nums: List[int]) -> int: | ||
low = 0 | ||
# start with the full range of the array | ||
high = len(nums) - 1 | ||
|
||
# find the middle index | ||
while low < high: | ||
mid = low + (high - low) // 2 | ||
|
||
# if mid is greater than the last element, the min must be on the right | ||
if nums[mid] > nums[high]: | ||
# move the low pointer to the right | ||
low = mid + 1 | ||
else: | ||
# min could be mid or in the left part | ||
high = mid | ||
# low and high converge to the minimum element | ||
return nums[low] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# Time Complexity: O(n) - traverse the linked list at most once. | ||
# Space Complexity: O(1) - only use two pointers, no extra memory. | ||
|
||
class Solution: | ||
def hasCycle(self, head: Optional[ListNode]) -> bool: | ||
# two pointers for fast moves twice as fast as slow. | ||
fast = head | ||
slow = head | ||
|
||
# loop the list while fast and fast.next exist. | ||
while fast and fast.next: | ||
# move fast pointer two steps. | ||
fast = fast.next.next | ||
# move slow pointer one step. | ||
slow = slow.next | ||
|
||
# if they meet, there's a cycle. | ||
if fast == slow: | ||
return True | ||
return False | ||
|