zoukankan      html  css  js  c++  java
  • 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;
        }
    
  • 相关阅读:
    npm 之 --save , -D,--save -dev的区别
    webpack 之 打包(最新版)
    npm 与 yarn 对比
    webpack 之 打包图片文件
    webpack 之 打包less文件
    javascript 之 Event Loop
    package.json中type的含义
    webpack 之 打包css文件操作
    常见问题 之 webpack打包css问题
    类方法和对象方法
  • 原文地址:https://www.cnblogs.com/ydlme/p/4589402.html
Copyright © 2011-2022 走看看