Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created June 16, 2014 01:41
Show Gist options
  • Save Ray1988/13e72011c9b843bc6282 to your computer and use it in GitHub Desktop.
Save Ray1988/13e72011c9b843bc6282 to your computer and use it in GitHub Desktop.
java
/*
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.
*/
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix==null || matrix.length==0){
return false;
}
int start=0;
int end=matrix.length*matrix[0].length-1;
while (start<=end){
int mid=start+(end-start)/2;
int candidate=matrix[mid/matrix[0].length][mid%matrix[0].length];
if (candidate==target){
return true;
}
else if (candidate<target){
start=mid+1;
}
else{
end=mid-1;
}
}
return false;
}
}
@chaoweimt
Copy link

see [][] de 第一个是生效的 其他的不生效

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment