Created
June 16, 2014 01:41
-
-
Save Ray1988/13e72011c9b843bc6282 to your computer and use it in GitHub Desktop.
java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see [][] de 第一个是生效的 其他的不生效