Have to say the code with loop is more fancy, but for large data set, first locate the ROW then implement the BST will definitely faster than loop search.
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null) {
return false;
}
if (matrix.length == 0 || matrix[0].length == 0) {
return false;
}
//lg m + n
// int i = 0;
// int j = matrix[0].length - 1;
// while( i < matrix.length){
// if(matrix[i][j] < target){
// i++;
// }else{
// break;
// }
// }
// if(i >= matrix.length){
// return false;
// }
//return isExistBS(matrix, i, 0, matrix[0].length-1, target);
// m+n
int i = matrix.length - 1;
int j = 0;
while (i >= 0 && j <= matrix[0].length - 1) {
if (target > matrix[i][j]) {
j = j + 1;
} else if (target < matrix[i][j]) {
i = i - 1;
} else {
return true;
}
}
return false;
}
private boolean isExistBS(int[][] matrix, int curRow, int start, int end, int target){
if(matrix[curRow][start] == target || matrix[curRow][end] == target){
return true;
}
if(start == end || end - start == 1){
return false;
}
int n = (start + end) / 2;
if(matrix[curRow][n] == target){
return true;
}
if(matrix[curRow][n] > target){
return isExistBS(matrix, curRow, start, n, target);
}else{
return isExistBS(matrix, curRow, n, end, target);
}
//return isExistBS(matrix, curRow, start, n, target) || isExistBS(matrix, curRow, n, end, target);
}
}
没有评论:
发表评论