Skip to content
Open
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
30 changes: 30 additions & 0 deletions leetcode33.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Time Complexity: O(log n)
# Space Complexity: O(1)
# Did this code successfully run on LeetCode: Yes

class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]: #left half is sorted
if nums[low] <= target and nums[mid] >= target:
high = mid - 1
else:
low = mid + 1
else: #right half is sorted
if nums[mid] <= target and nums[high] >= target:
low = mid + 1
else:
high = mid - 1

return -1


24 changes: 24 additions & 0 deletions leetcode702.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Time Complexity: O(log p)
# Space Complexity: O(1)
# Did this code successfully run on LeetCode: I don't have premium account to check it on Leetcode, but I have tested it

class Solution(object):
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
l, h = 0, 1
while reader.get(h) < target:
l = h
h *= 2
while l <= h:
mid = (l + h) // 2
if reader.get(mid) == target:
return mid
elif reader.get(mid) < target:
l = mid + 1
else:
h = mid - 1
return -1
24 changes: 24 additions & 0 deletions leetcode74.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Time Complexity: O(log(m * n))
# Space Complexity: O(1)
# Did this code successfully run on LeetCode: Yes

class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m, n = len(matrix), len(matrix[0])
l, h = 0, m * n - 1
while l <= h:
mid = (l + h) // 2
r, c = mid // n, mid % n
if matrix[r][c] == target:
return True
elif matrix[r][c] < target:
l = mid + 1
else:
h = mid - 1
return False