1. 题目描述
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
题目给定了一个m行n列的二维数组,数组中的数据有两个特点,即
① 每一行中的数据从左到右递增
② 每一列中的数据从上到下递增
给定一个目标数字,找到一个高效(不遍历二维数组)的算法来解决这个问题。
2. 解题思路
从右上角开始比较,如果当前数值大于target则此列不可能出现target ->往左走 j–,如果当前数值小于target则此行不可能出现target ->往下走i++
3. Code
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int i(0), j(matrix[i].size()-1);
while(i < matrix.size() && j >= 0) // 当数组没有越界时
{
if(matrix[i][j] == target) // 找到目标返回true
return true;
else if(matrix[i][j] > target) // 如果大于只能往左走
--j;
else if(matrix[i][j] < target) // 如果小于只能往下走
++i;
}
return false;
}
};