搜索二维矩阵

我的笨思路:遍历行首,目标值大于本行首值小于下一行首值时,遍历列,找到目标值返回true,如果前n-1行没找到,遍历最后一行,找到目标值返回true。

官方思路:二分查找法
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int low = 0, high = m * n - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
int x = matrix[mid / n][mid % n];
if (x < target) {
low = mid + 1;
} else if (x > target) {
high = mid - 1;
} else {
return true;
}
}
return false;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/sou-suo-er-wei-ju-zhen-by-leetcode-solut-vxui/
来源:力扣(LeetCode)
时间复杂度:O(logmn),其中 mm 和 nn 分别是矩阵的行数和列数。
空间复杂度:O(1)

浙公网安备 33010602011771号