LeetCode Search a 2D Matrix

2015-07-24 06:51:49 · 作者: · 浏览: 56

?

?

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 from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

    ?

    For example,

    Consider the following matrix:

    [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    

    Given target = 3, return true.


    由于这个矩阵是有序的,我们可以从右上角开始进行比较,若比右上角大,则肯定在下一行,否则就在本行中,时间复杂度O(m+n)

    ?

    当然也可以用二分来做,同样从最右边那一列开始看,先二分出是在哪一行,然后再二分出是在哪一列时间复杂度 O(logn+logm)

    ?

    下面给出O(m+n)的代码

    ?

    ?

    class Solution {
    public:
        bool searchMatrix(vector
        
          > &matrix, int target) {
            int m=matrix.size();
            int n=matrix[0].size();
            if(matrix.empty()||matrix[0].empty()) return false;
            int x=0,y=n-1;
            while(x>=0&&x
         
          =0&&y
          
           target) y--; else x++; } return false; } }; 
          
         
        


    ?