原题链接: https://leetcode.com/problems/search-a-2d-matrix-ii/description/
原题描述: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
(1)Integers in each row are sorted in ascending from left to right.
(2)Integers in each column are sorted in ascending from top to bottom.
Solution: 给定的m x n矩阵的每一行和每一列都是有序的,所以我们可以从矩阵右上角的那个元素比较,当matrix[i][j]比target大的话,说明target只会出现在当前位置的左边,因此只需左移一步;当matrix[i][j]比target小的话,说明target只会出现在当前位置的下面,因此只需往下移一步。这样,直到遍历到最左下角的元素,若能找到target则返回true,否则返回false。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty()) return false;
int m = matrix.size(), n = matrix[0].size();
if (!n) return false;
int c = n - 1, r = 0;
while(r < m && c >= 0) {
if (matrix[r][c] == target) return true;
else if (matrix[r][c] > target) c--;
else r++;
}
return false;
}
};
算法复杂度: O(m+n)。