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
40 changes: 40 additions & 0 deletions 01-Search a 2D Matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Problem 1 - Search a 2D Matrix (https://leetcode.com/problems/search-a-2d-matrix/)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# m, n = len(matrix), len(matrix[0])
# t = m * n
# l = 0
# r = t - 1

# while l <= r:
# m = (l + r) // 2
# i = m // n
# j = m % n

# mid_num = matrix[i][j]

# if target == mid_num:
# return True
# elif target > mid_num:
# l = m + 1
# else:
# r = m -1
# return False
if matrix == None or len(matrix) == 0:
return False
m = len(matrix)
n = len(matrix[0])
low = 0
high = m * n - 1

while low <= high:
mid = low + (high - low) // 2
row = mid // n
col = mid % n
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
low = mid + 1
else:
high = mid - 1
return False
28 changes: 28 additions & 0 deletions 02-Search in Rotated Sorted Array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Problem 2 - Search in Rotated Sorted Array (https://leetcode.com/problems/search-in-rotated-sorted-array/)
class Solution:
def search(self, nums: List[int], target: int) -> int:
if nums == None or len(nums) == 0:
return -1

n = len(nums)
low = 0
high = n - 1

while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
# left sorted
if nums[low] <= nums[mid]:
# check if num lies in sorted part
if nums[low] <= target and nums[mid] > target:
high = mid - 1
else:
low = mid + 1
# right sorted
else:
if nums[mid] < target and nums[high] >= target:
low = mid + 1
else:
high = mid - 1
return -1
27 changes: 27 additions & 0 deletions 03-Search in a Sorted Array of Unknown Size.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Search in a Sorted Array of Unknown Size (https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/)
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
#class ArrayReader:
# def get(self, index: int) -> int:

class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
low = 0
high = 1

while reader.get(high) < target:
low = high
high = 2 * high

while low <= high:
mid = (low + high) // 2
if reader.get(mid) == target:
return mid
elif reader.get(mid) < target:
low = mid + 1
else:
high = mid - 1

return -1