题目:
写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
给出 target = 3
,返回 true
解法一:暴力方式,全部遍历一边
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==0|| matrix[0].length == 0){
return false;
}
int m=matrix.length;
int n=matrix[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==target){
return true;
}
}
}
return false;
}
}
解法二:用二分法解决
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==0|| matrix[0].length == 0){
return false;
}
int m=matrix.length;
int n=matrix[0].length;
int len=m*n;
int right=len-1;
int left=0;
int mid;
while(left<=right){
mid=(left+right)/2;
if(matrix[mid/n][mid%n]==target){
return true;
}
else if(matrix[mid/n][mid%n]>target){
right=mid-1;
}else{
left=mid+1;
}
}
return false;
}
}
然而,最后两种方法运行的时间居然差不多!!!惊呆了!!!