解題思路
從右上角開始查找。矩陣中的一個數,它左邊的數都比它小,下邊的數都比它大。因此,從右上角開始查找,就可以根據 target 和當前元素的大小關係來縮小查找區間。
複雜度:O(M + N) + O(1)
public boolean Find(int target, int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return false;
int rows = matrix.length, cols = matrix[0].length;
int r = 0, c = cols - 1; // 從右上角開始
while (r <= rows - 1 && c >= 0) {
if (target == matrix[r][c])
return true;
else if (target > matrix[r][c])
r++;
else
c--;
}
return false;
}