Task
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.
Example
Example 1:
1
2
3
4
5
6
7
8
|
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
|
Example 2:
1
2
3
4
5
6
7
8
|
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
|
Solution
- 整个矩阵拉成一维数组是升序排列,故用二分搜索
- 时间复杂度:O(log(m*n))
- 空间复杂度:O(1)
- 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// Runtime: 20 ms, faster than 24.78% of C++ online submissions for Search a 2D Matrix.
// Memory Usage: 11.5 MB, less than 18.00% of C++ online submissions for Search a 2D Matrix.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
//边界
if(matrix.size()==0)
return false;
//得到矩阵宽高
int H=matrix.size(),W=matrix[0].size();
int l=0,r=H*W;
while(l<r){
int m=l+(r-l)/2;
//将拉成一维矩阵后的位置转换为矩阵中的坐标
int val=matrix[m/W][m%W];
if(val<target)
l=m+1;
else if(val>target)
r=m;
else
return true;
}
return false;
}
};
|