28. 搜索二维矩阵
写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
给出 target = 3
,返回 true
挑战
O(log(n) + log(m)) 时间复杂度
public class Solution {
/**
* @param matrix: matrix, a list of lists of integers
* @param target: An integer
* @return: a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
if(matrix==null || matrix.length<1)
{
return false;
}
int r=0;
int c=matrix[0].length-1;
while(r<matrix.length && c>=0)
{
if(matrix[r][c]<target)
{
r++;
}else if(matrix[r][c]>target)
{
c--;
}else
{
return true;
}
}
return false;
}
}
###########################################################
class Solution {
public:
/**
* @param matrix: matrix, a list of lists of integers
* @param target: An integer
* @return: a boolean, indicate whether matrix contains target
*/
bool searchMatrix(vector<vector<int>> &matrix, int target) {
// write your code here
if(matrix.size()<1) return 0;
int r=matrix.size();
int c=matrix[0].size();
int L=0;
int R=r*c-1;
while(L<=R)
{
int mid=L+((R-L)>>1);
int midNumber=matrix[mid/c][mid%c];
if(midNumber>target)
{
R=mid-1;
}else if(midNumber<target)
{
L=mid+1;
}else
{
return true;
}
}
return false;
}
};
#############################################################
class Solution:
"""
@param matrix: matrix, a list of lists of integers
@param target: An integer
@return: a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if len(matrix)<1:
return False
r=len(matrix)
c=len(matrix[0])
L=0
R=r*c-1
while L<=R:
mid=L+((R-L)>>1)
midN=matrix[int(mid/c)][int(mid%c)]
if midN>target:
R=mid-1
elif midN<target:
L=mid+1
else:
return True
return False