// 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;
}
असल में, हम द्विआधारी खोज दो बार उपयोग कर सकते हैं, द्विआधारी खोज द्वारा लक्ष्य पंक्ति खोजें पहले, तो द्विआधारी खोज के द्वारा लगातार लक्ष्य मिल जाए, तो समय जटिलता ओ (LGX) + O (lgy) है , ओ (एलजीएक्स + एलजीई) है, ओ (एक्स + वाई) बेहतर है।
स्रोत
2014-11-12 06:03:17
इस http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-algorithms-10 –