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.
Idea: Any m*n two-dimension array is an one-dimension array with m*n elements, where two[i][j]=one[i*n+j]. So this is actually a problem of binary search in an one-dimension array with m*n elements.
Time: O(lg(mn)) Space: O(1)
Code:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m=matrix.length;
int n=matrix[0].length;
int start=0;
int end=m*n-1;
while(start<=end)
{
int mid=(start+end)/2;
int digit=matrix[mid/n][mid%n];
if(digit==target)
return true;
if(digit<target)
start=mid+1;
else
end=mid-1;
}
return false;
}
}
No comments:
Post a Comment