problem
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.
Analysis
因为现在整个二维数组是相对有序的,所以我们可以通过观察和题目给的条件发现,一个元素它的下面那个元素肯定比它大,它右边的元素肯定比它小,所以从右上角开始(也可以从其他四个角开始),对每一个元素,判断它和target的大小,如果它比target大,target肯定出现在它右边,新的元素就变成了当前元素的右边那个元素。如果它比target小,说明target肯定出现在它的下面,所以,当前元素变成下面的那个。如果搜索到左下角附近合法的区域仍然没有找到的话,说明并不能在这个矩阵中找到target,返回false。
Complexity
时间复杂度:
O(n+m)
(m,n分别是二维数组的两个维度的大小)
空间复杂度:
O(1)
Code
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0) return false;
int r = 0;
int c = matrix[0].size()-1;
int m = matrix.size();
int n = c + 1;
while (r < m && c >= 0) {
if (matrix[r][c] == target) return true;
if (matrix[r][c] > target) {
c -= 1;
} else {
r += 1;
}
}
return false;
}
};