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.
- Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true - Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
解法一
采用二分法,先跟mid行的最后一个比较,若target较大,则start=mid+1;相等则返回true;较小则跟mid行第一个比较,若target较小则end=mid-1;若相等返回true;若较大则在mid行开始二分法,如果没找到target返回false,找到了则返回true
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0||matrix==null||matrix[0].length==0)
return false;
int n=matrix.length,m=matrix[0].length;
int start=0,end=n-1;
while(start<=end)
{
int mid=(start+end)/2;
if(matrix[mid][m-1]==target)
return true;
else if (matrix[mid][m-1]<target)
start=mid+1;
else
if(matrix[mid][0]==target)
return true;
else if(matrix[mid][0]>target)
end=mid-1;
else
{
int startr=0,endr=m-1;
while(startr<=endr)
{
int midr=(startr+endr)/2;
if(matrix[mid][midr]==target)
return true;
else if(matrix[mid][midr]>target)
endr=midr-1;
else
startr=midr+1;
}
return false;
}
}
return false;
}
Runtime: 4 ms, faster than 100.00% of Java online submissions for Search a 2D Matrix.
Memory Usage: 38.8 MB, less than 66.05% of Java online submissions for Search a 2D Matrix.
解法二
可以只用一次二分搜索,即把二维数组转化为一维数组,那么一维数组中的matrix[k]就相当于二维数组中的matrix[k/m][k%m]
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0||matrix==null)
return false;
int n=matrix.length,m=matrix[0].length;
int start=0,end=n*m-1;
while(start<=end)
{
int mid=(start+end)/2;
if(matrix[mid/m][mid%m]==target)
return true;
else if(matrix[mid/m][mid%m]<target)
start=mid+1;
else
end=mid-1;
}
return false;
}
python
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
n=len(matrix)
if n==0:
return False
m=len(matrix[0])
if m==0:
return False
start,end=0,n*m-1
while start<=end:
mid=(start+end)//2
if matrix[mid//m][mid%m]==target:
return True
elif matrix[mid//m][mid%m]<target:
start=mid+1
else:
end=mid-1
return False
Runtime: 52 ms, faster than 26.19% of Python3 online submissions for Search a 2D Matrix.
Memory Usage: 13.8 MB, less than 5.71% of Python3 online submissions for Search a 2D Matrix.