74.Search a 2D Matrix
给定一个矩阵,和一个整数,矩阵是从左到右,从上到下有序的,求,这个给定的整数是否在有序的矩阵中。
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
思路:
对于有序的查找,首先想到就是二分查找,这个题也是一样,只不过是变为有序的矩阵而已。将矩阵看做一个一维的数组,利用一维的二分查找方法,对每一次的 mid ,换算为矩阵的坐标即可。
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.size() == 0 || matrix[0].size() == 0) return false; int row = matrix.size(), col = matrix[0].size(); int n = row * col, left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; int x = mid / col, y = mid % col; if (matrix[x][y] == target) return true; else if (matrix[x][y] > target) right = mid - 1; else left = mid + 1; } return false; } };