• 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;        
        }        
    };
  • 相关阅读:
    golang的select典型用法
    vscode配置git和提交代码到github教程
    VsCode中好用的git源代码管理插件GitLens
    GoMock框架使用指南
    golang对结构体排序,重写sort
    Go语言开发Prometheus Exporter示例
    golang 字符串拼接性能比较
    golang中的strings.Compare
    各大厂分布式链路跟踪系统架构对比
    NV triton启动方式说明
  • 原文地址:https://www.cnblogs.com/graph/p/3217813.html
Copyright © 2020-2023  润新知