美文网首页Leetcode刷题记录
Leetcode 240. Search a 2D Matrix

Leetcode 240. Search a 2D Matrix

作者: xiaohanhan1019 | 来源:发表于2020-01-07 13:23 被阅读0次

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;
    }
};

相关文章

网友评论

    本文标题:Leetcode 240. Search a 2D Matrix

    本文链接:https://www.haomeiwen.com/subject/dnuractx.html