zoukankan      html  css  js  c++  java
  • 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;        
        }        
    };
  • 相关阅读:
    清北刷题班day3 morning
    [NOI1997] 积木游戏(dp)
    [NOI1999] 棋盘分割(推式子+dp)
    2017北京国庆刷题Day7 afternoon
    湖南集训day8
    湖南集训day7
    湖南集训day6
    湖南集训day5
    湖南集训day4
    湖南集训day3
  • 原文地址:https://www.cnblogs.com/graph/p/3217813.html
Copyright © 2011-2022 走看看