74. Search a 2D Matrix
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.
Show Tags Show Similar Problems
A linear solution
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int i = matrix.length -1;
int j = matrix[0].length -1;
if(target > matrix[i][j] || target < matrix[0][0] ) return false;
int x = 0;
int y = j;
while(x <= i&& y>=0){
if(target == matrix[x][y]) return true;
else if( target < matrix[x][y]){
y--;
}else{
x++;
}
}
return false;
}
}
2 binary search
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int k = matrix[0].length -1;
// find the row that matrix[r][k] > target && matrix[r-1][k] < target;
int t = 0;
int b = matrix.length -1;
if(target < matrix[0][0] || target > matrix[matrix.length-1][matrix[0].length-1]) return false;
while(t <= b){
int mid = t + (b-t)/2;
if(matrix[mid][k] == target) return true;
if(matrix[mid][k] > target){
b = mid-1;
}else{
t = mid+1;
}
}
int l = t;
t = 0;
b = matrix[0].length -1;
while(t <= b){
int mid = t + (b-t)/2;
if(matrix[l][mid] == target) return true;
if(matrix[l][mid] > target){
b = mid -1;
}else{
t = mid + 1;
}
}
return false;
}
}
1 binary search
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
int l = 0;
int r = row * col - 1;
while(l <=r ){
int mid = l + (r-l)/2;
int val = matrix[mid/col][mid%col];
if(val == target) return true;
if(val > target){
r = mid-1;
}else{
l = mid+1;
}
}
return false;
}
}