28, two-dimensional matrix search

Title: prepared by an efficient algorithm to search  m  X  n-  matrix of a matrix target value target. This matrix has the following characteristics:

  • Elements of each row in ascending order from left to right.
  • Element of each column from top to bottom in ascending order.

Ideas: This question has long ago learned related solution, so one can see there ideas.

   This question is characterized by: the upper right corner of the largest element in a row, in a column to a minimum. Therefore, when it is larger than a number, certainly move downward in the column direction, when a ratio of the number of hours it is certainly moved to the left in the row direction.

   So to compare the target and the upper right corner functions.

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

 

Guess you like

Origin www.cnblogs.com/roscangjie/p/10949959.html