题目:给定一个有序的二维数组,判断数组中是否存在target
算法:逐行进行二分查找
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for (int i=0; i<matrix.length; ++i) {
if (horizontalBinarySearch(matrix, target, matrix[i].length, i)) {
return true;
}
}
return false;
}
/**
* Binary Search horizontal
* @param matrix
* @param target
* @param length
* @param row
* @return
*/
public boolean horizontalBinarySearch(int[][] matrix, int target, int length, int row) {
int mid = 0;
int left = 0;
int right = length - 1;
while (left <= right) {
mid = (left + right) / 2;
if (target == matrix[row][mid]) {
return true;
} else if (target < matrix[row][mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return false;
}
}