Leetcode 240. Search a 2D Matrix II

Leetcode 240. Search a 2D Matrix II

题目链接

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.

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.

思路

从右上角A_{0,m-1}开始,如果A_{0,m-1} > target则往左走,如果A_{0,m-1} < target则往下走,直到找到target,时间复杂度O(n)

Q1:为什么往下走以后不需要考虑往右走的情况?

A1:如下图(只是一个局部),比如target为20,当前走到了22的位置,那么这时候他选择往左走走到16,再往下走走到17,它不需要往右走去检查24,因为24这个位置的数根据题意必然大于22,所以不需要考虑。向左走相当于排除了一整列,所以没有必要再往右走
\left( \begin{array}{c} 16 & 22 \\ 17 & 24 \end{array} \right)

代码

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.size()<1){
            return false;
        }
        int n=matrix.size();
        int m=matrix[0].size();
        int x=0;
        int y=m-1;
        while(x<n && y>=0){
            if(matrix[x][y]>target){
                y--;
            }else if(matrix[x][y]<target){
                x++;
            }else{
                return true;
            }
        }
        return false;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。