LeetCode_Search a 2D Matrix

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]

]
class Solution {

public:

    bool searchMatrix(vector<vector<int> > &matrix, int target) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

         int m = matrix.size();

        int n = matrix[0].size();

        if(target < matrix[0][0]  || target >matrix[m-1][n-1])return false;

        

        int i,j;

        

        for(i = 0 ;i< m-1;i++)

            if(target >=matrix[i+1][0])

              continue;

            else

               break ;

               

        for(j = 0; j< n; j++)

            if(target == matrix[i][j])

              return true;

              else if(target <matrix[i][j])

               return false;

    }

};

 感觉上面的方法虽然过了所有case,但还是可能有问题的,看了《剑指offer》后,才发现了一种更好的解法:

class Solution {

public:

    bool searchMatrix(vector<vector<int> > &matrix, int target) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        int m = matrix.size();

        int n = matrix[0].size();

        

        int row = 0, column = n -1;

        while(row < m && column >= 0)

        {

        

            if(matrix[row][column] == target)

                 return true;

            else if(matrix[row][column] > target)

                    column--;

                else

                     row++;

        }        

        return false;        

    }        

};

 

你可能感兴趣的:(LeetCode)