题目链接:Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
这道题的要求是在m*n的矩阵中查找指定元素target。而且矩阵中每行都有序,且每行的第一个元素均大于其前一行的最后一个元素。
思路就是一句话:把二维数组当成一个有序数组,直接二分搜索。
时间复杂度:O(log(m+n))
空间复杂度:O(1)
1 class Solution
2 {
3 public:
4 bool searchMatrix(vector<vector<int> > &matrix, int target)
5 {
6 int m = matrix.size(), n = matrix[0].size();
7
8 int l = 0, r = m * n - 1;
9 while(l <= r)
10 {
11 int mid = (l + r) / 2;
12 if(matrix[mid / n][mid % n] == target)
13 return true;
14 else if(matrix[mid / n][mid % n] > target)
15 r = mid - 1;
16 else
17 l = mid + 1;
18 }
19
20 return false;
21 }
22 };