• 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.

    根据矩阵的性质可知

    • 先判断该target可能所在的行
    • 然后在判断改行中是否出现该值
    • 两次判断都可以用二分

    所以复杂度为O(log(n))
    代码如下:

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.size() == 0)
                return false;
    
            int b = 0, e = matrix.size()-1;
            while(b < e)
            {
                int mid = b + (e - b + 1) / 2;
                if(matrix[mid][0] == target)
                    return true;
                else if(matrix[mid][0] < target)
                    b = mid;
                else
                    e = mid - 1;
            }
            int x = 0, y = matrix[b].size() - 1;
            while(x < y)
            {
                int mid = x + (y - x + 1) / 2;
                if(matrix[b][mid] == target)
                    return true;
                else if(matrix[b][mid] < target)
                    x = mid;
                else
                    y = mid - 1;
            }
            if(b < matrix.size() && x < matrix[b].size() && matrix[b][x] == target)
                return true;
            return false;
        }
    };
    
  • 相关阅读:
    Java(15) _Runtime类 内存方法
    Mysql(1)_ 基本sql语句
    Java(13)_ 用IO流复制文件
    Java(12)_switch语句
    Java(10) _无参构造方法调用问题
    Java(9) _强制类型转换
    Java(8)_符串常量赋值
    Java(7)_file类的常用方法
    Java(6)_ Runtime类调用exe程序
    Java(5) _类的定义
  • 原文地址:https://www.cnblogs.com/aiterator/p/6710482.html
Copyright © 2020-2023  润新知