Thought:
First find the row and then find the column.
Code:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0) return false;
int m = matrix.length, n = matrix[0].length;
int[] a = new int[m];
for (int i = 0; i < m; i++) a[i] = matrix[i][0];
int row = helper(a, target);
if (row == -1) return false;
int col = helper(matrix[row], target);
return matrix[row][col] == target;
}
public int helper (int[] a, int x) {
int start = 0, end = a.length - 1, mid = (a.length - 1) / 2;
int ret = -1;
while (start <= end) {
if (a[mid] > x) {
end = mid - 1;
mid = (start + end) / 2;
}else {
start = mid + 1;
ret = mid;
mid = (start + end) / 2;
}
}
return ret;
}
}
No comments:
Post a Comment