// 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;
}
Trên thực tế, chúng ta có thể sử dụng tìm kiếm nhị phân hai lần, tìm hàng mục tiêu bằng cách tìm kiếm nhị phân đầu tiên, sau đó tìm mục tiêu ở hàng bằng cách tìm kiếm nhị phân, vì vậy mức độ phức tạp thời gian là O (LGX) + O (lgy) , là O (lgx + lgy), tốt hơn O (x + y).
Nguồn
2014-11-12 06:03:17
có vẻ tương tự như http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-algorithms-10 –