Question
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
Analysis
Step
Since matrix is sorted, it is highly possible that binary search is needed. We easily get the idea that use binary search twice to find which row that target lies, and then find whether it exists in that row.
How
The difficult thing is that in the first binary search our goal is to find the maximum number that is less than target, or -1 if not found.
In the standard binary search, it stops when left>right, and returns false (means not found). However, in the first binary search of this problem, it must return one value ( =-1 if it is less than the first element, =last element if it is greater than the last element.). If thinking it in a smart way, “right” is the correct one to return.
If we want to find the smallest one that is greater than target, “left” should be returned.
So the difference is that when left > right, what value should be return.
General binary search
def search(array, target, left, right):
if left>right:
return Specific_value #Specific_value is defined by ourselves
mid = (left + right)/2
if array[mid]==target:
return Specific_value
elif: array[mid]<target:
return search(array, target, mid+1, right)
else:
return search(array, target, left, mid-1)
If two arrays are presented in the same way, the two modified binary search can be merged into one.
My Solution
class Solution:
# @param {integer[][]} matrix
# @param {integer} target
# @return {boolean}
def searchMatrix(self, matrix, target):
if matrix==None or len(matrix)==0 or len(matrix[0])==0:
return False
ind1 = self.subsearch(matrix, target, 0, len(matrix)-1)
if ind1==-1:
return False
else:
ind1array = matrix[ind1]
return self.bisearch(ind1array,target, 0,len(ind1array)-1)
def subsearch(self, matrix, target,left,right):
if left>right:
return right
mid = (left + right)/2
if matrix[mid][0]==target:
return right
elif matrix[mid][0]<target:
return self.subsearch(matrix,target,mid+1,right)
else:
return self.subsearch(matrix,target,left,mid-1)
def bisearch(self, array, target, left, right):
if left > right:
return False
mid = (left + right)/2
if array[mid]==target:
return True
elif array[mid]<target:
return self.bisearch(array, target, mid+1, right)
else:
return self.bisearch(array, target, left, mid-1)