【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.

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.

 

题意:

  给一个二维矩阵,该矩阵满足从左到右、从上到下元素值递增。给定一个数,判断该数是否包含在数组中。

思路:

  利用矩阵的性质,从右上角开始比较。若右上角的元素小于目标值,说明目标值在该元素的下方,则向下一行进行比较。若右上角的元素大于目标值,说明目标值在该元素的左边,则向左一列进行比较。例如查找元素5:

[
  [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]
]                                       15 > 5,向左一列比较

[
  [1,   4,  7, 11, --],
  [2,   5,  8, 12, --],
  [3,   6,  9, 16, --],
  [10, 13, 14, 17, --],
  [18, 21, 23, 26,--]
]                                       11 > 5,向左一列比较   

[
  [1,   4,  7, --, --],
  [2,   5,  8, --, --],
  [3,   6,  9, --, --],
  [10, 13, 14, --, --],
  [18, 21, 23, --,--]
]                                       7 > 5,向左一列比较

[
  [1,   4,  --, --, --],
  [2,   5,  --, --, --],
  [3,   6,  --, --, --],
  [10, 13, --, --, --],
  [18, 21, --, --,--]
]                                       4 < 5,向下一行比较

[
  [--,   --,  --, --, --],
  [2,   5,  --, --, --],
  [3,   6,  --, --, --],
  [10, 13, --, --, --],
  [18, 21, --, --,--]
]                                      找到目标5,return true

  可以看出,每一次比较都排除了一行(或者一列)的元素,比起暴力查找,快了不少。

C++:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        //获得矩阵高度
        unsigned int height = matrix.size();
        if(height == 0)
            return false;
        
        //获得矩阵宽度
        unsigned int width = matrix[0].size();
        
        //定位x、y为矩阵右上角坐标
        int x = 0, y = width - 1;
        
        while(x < height && y >= 0)
        {
            if(matrix[x][y] == target) //matrix[x][y]若等于目标元素,返回true
                return true;
            if(matrix[x][y] < target)  //matrix[x][y]若小于目标元素,向下移动
                x++;
            else                       //matrix[x][y]若大于目标元素,向左移动  
                y--;
        }
        
        //出了边界还未找到,说明没有目标元素,返回false
        return false;
    }
};

  

posted @ 2015-07-23 13:57  tjuloading  阅读(159)  评论(0编辑  收藏  举报