• [leetcode-74-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]
    ]
    Given target = 3, return true.

    思路:

    二分查找。将矩阵看成是一维的,索引为

    matrix[middle / col][middle%col]
    bool searchMatrix(vector<vector<int>>& matrix, int target)
         {
             if (matrix.size() == 0) return false;
            
             int row = matrix.size(), col = matrix[0].size();
             int left = 0, right = row*col - 1, middle = left + (right - left) / 2;
             
             while (left <= right)
             {
                 middle = left + (right - left) / 2;
                 if (target == matrix[middle / col][middle%col])return true;
                 else if (target < matrix[middle / col][middle%col])right = middle - 1;
                 else left = middle + 1;
             }
             return false;         
         }
  • 相关阅读:
    php实现频率限制
    手机号打码
    qxx项目大文件上传
    502错误
    mac 安装phpunit
    文件权限问题
    无题
    php安装redis扩展全
    linux中whereis、which、find、location的区别和用法
    php安装redis扩展
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6931134.html
Copyright © 2020-2023  润新知