240. Search a 2D Matrix II 题解

来源:互联网 发布:中国电信2g网络制式 编辑:程序博客网 时间:2024/05/18 06:25

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.

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.



题目链接:240. Search a 2D Matrix II



算法描述:


           由题意知,给定一个二维矩阵,该二维矩阵每行元素从左到右递增排列,每列元素从上到下递增排列。我们需要在这个矩阵中找到一个目标值 “target” ,且运用复杂度小的搜索算法。


         我们不能按照简单的遍历算法来做,可以按照这样的思路:在矩阵中找到一个合理的“中间”位置,这个“中间”位置可以很方便的在矩阵中遍历到其它元素,这个“中间”位置即矩阵的右上角位置,我们比较这个值与目标值 “target” 的大小关系,当目标值 “target” 大于这个位置的值,由于矩阵中元素的排列关系,我们只能继续向下查找。当目标值 “target” 小于这个位置的值时,我们向左查找。可以想象,查找的路线为 “阶梯形” 。

         

          如果查找的位置超过矩阵的边界,则返回 false。



代码:

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        if(matrix.size() == 0 || matrix[0].size() == 0){            return false;        }                int i = 0;        int j = matrix[0].size()-1;                while(i<matrix.size() && j>=0){            if(matrix[i][j] == target){                return true;            }            else if(matrix[i][j] > target){                j--;            }            else{                i++;            }        }        return false;    }};




0 0