写出一个高效的算法来搜索 m × n矩阵中的值。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每行的第一个数大于上一行的最后一个整数。
-
考虑下列矩阵:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
给出
target = 3
,返回true
public class Solution {
/**
* @param 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
int row = matrix.length;
if(row==0)
return false;
int col = matrix[0].length-1;
for(int i = 0 ; i < row; i++){
if(matrix[i][col] == target)
return true;
if(matrix[i][col] > target){
for(int j = 0;j<col;j++){
if(matrix[i][j] == target)
return true;
if(matrix[i][j]<target && matrix[i][j+1]>target)
return false;
}
}
}
return false;//针对数组只有一个数且不是target的情况
}
}
/**
* @param 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
int row = matrix.length;
if(row==0)
return false;
int col = matrix[0].length-1;
for(int i = 0 ; i < row; i++){
if(matrix[i][col] == target)
return true;
if(matrix[i][col] > target){
for(int j = 0;j<col;j++){
if(matrix[i][j] == target)
return true;
if(matrix[i][j]<target && matrix[i][j+1]>target)
return false;
}
}
}
return false;//针对数组只有一个数且不是target的情况
}
}
public class Solution {
/**
* @param 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
int row = matrix.length;
if(row==0)
return false;
int col = matrix[0].length;
int low = 0;
int high = row*col-1;
while(low + 1 < high){//最后low和high挨着的时候就跳出循环
int mid = (low + high)/2;
int r = mid / col;//行坐标
int c = mid % col;//列坐标
if(matrix[r][c] == target)
return true;
else if(matrix[r][c] < target)
low = mid;
else
high = mid;
}
//循环结束 判断一下最后相邻的low和high
if(matrix[low/col][low%col]==target)
return true;
if(matrix[high/col][high%col]==target)
return true;
return false;
}
}
/**
* @param 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
int row = matrix.length;
if(row==0)
return false;
int col = matrix[0].length;
int low = 0;
int high = row*col-1;
while(low + 1 < high){//最后low和high挨着的时候就跳出循环
int mid = (low + high)/2;
int r = mid / col;//行坐标
int c = mid % col;//列坐标
if(matrix[r][c] == target)
return true;
else if(matrix[r][c] < target)
low = mid;
else
high = mid;
}
//循环结束 判断一下最后相邻的low和high
if(matrix[low/col][low%col]==target)
return true;
if(matrix[high/col][high%col]==target)
return true;
return false;
}
}