// the matrix is like this, from left to right is ascending, and
// from down to up is ascending, but the second row'start is not always bigger than the first row's end, which is diff from [leetcode]https://oj.leetcode.com/problems/search-a-2d-matrix/
// 1 5 7 9
// 4 6 10 15
// 8 11 12 19
// 14 16 18 21
// time complexity is O(x+y), x is the count of row, and y is the count of column
public boolean searchMatrix2(int[][] matrix, int target) {
int rowCount = matrix.length;
if(rowCount == 0) return false;
int colCount = matrix[0].length;
if(colCount == 0) return false;
//first find the target row, needs O(x)
int targetRow = 0;
while(targetRow < rowCount-1 && matrix[targetRow+1][0] <= target) {
targetRow++;
}
//than find the target in the target row, needs O(y), so the total is O(x)+O(y)
boolean result = false;
for(int i = 0; i < colCount; i ++) {
if(matrix[targetRow][i] == target) {
result = true;
break;
}
}
return result;
}
En realidad, podemos usar la búsqueda binaria dos veces, encontrar la fila de destino mediante una búsqueda binaria en primer lugar, a continuación, encontrar el objetivo en la fila de búsqueda binaria, por lo que el tiempo de complejidad es O (lgx) + O (lgy) , es O (lgx + lgy), mejor el O (x + y).
suena similar a esto http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-algorithms-10 –