• Leetcode: Search a 2D Matrix


    Search a 2D Matrix

    Total Accepted: 43629 Total Submissions: 138231

     
     

    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.

    常规思路, 多次二分

    bool searchMatrix(vector<vector<int>>& matrix, int target) {
            if(matrix.empty())
                return false;
            vector<int> firstCol;
            for(auto v : matrix)
            firstCol.push_back(v[0]);
            if(binary_search(firstCol.begin(), firstCol.end(), target))
                return true; 
            vector<int>::iterator iter = lower_bound(firstCol.begin(), firstCol.end(), target);
            int low = iter - firstCol.begin();
            for(int i = 0; i < low; i++)
            {
                if(binary_search(matrix[i].begin(), matrix[i].end(), target))
                    return true;
            }
            return false;
        }
    

    投机取巧,存在潜在的bug

    bool searchMatrix(vector<vector<int> >& matrix, int target) {
            int rows = matrix.size();
            if (rows == 0)    return false;
            int cols = matrix[0].size();
            int first = 0, last = rows * cols - 1;
            if (target < matrix[0][0] || target > matrix[rows - 1][cols - 1])
                return false;
            int mid, val;
            // binary search
            while (first <= last) {
                mid = first + (last - first) / 2;
                val = matrix[mid / cols][mid % cols];
                if (val > target)
                    last = mid - 1;
                else if (val == target)
                    return true;
                else
                    first = mid + 1;
            }
            return false;
        }
    
  • 相关阅读:
    树莓派安装realvnc_server
    python中#!含义
    树莓派无显示屏连接wifi
    转载_fread函数详解
    树莓派3b+更改静态IP
    linux命令语法格式
    python-Arduino串口传输数据到电脑并保存至excel表格
    mysql的sql_mode合理设置
    Mysql 配置参数性能调优
    Kubernetes 部署 gitlab
  • 原文地址:https://www.cnblogs.com/ydlme/p/4589402.html
Copyright © 2020-2023  润新知