Skip to content

Instantly share code, notes, and snippets.

@rioshen
Last active August 29, 2015 14:00
Show Gist options
  • Save rioshen/11328307 to your computer and use it in GitHub Desktop.
Save rioshen/11328307 to your computer and use it in GitHub Desktop.
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
if not matrix or len(matrix) == 0:
return False
# Flatten the matrix into 1D array, complexity is O(K).
# K means the length of the new array.
array = []
for line in matrix:
array.extend(line)
return self.binary_search(array, target)
def binary_search(self, array, target):
start = 0
end = len(array) - 1
while start+1 < end:
mid = start + (end-start)/2
if array[mid] > target:
end = mid
elif array[mid] < target:
start = mid
else: # found the target
return True
if array[start] == target or array[end] == target:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment