zoukankan      html  css  js  c++  java
  • 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

    思路:1.二分比较判断可能在哪一行,确定searchRow,再在searchRow中二分找

    2. 当成线性表,来二分找。

    注意:这两个的复杂度???? 1.O(lgm+lgn) 2.O(lg(m*n))

    class Solution {
    public:
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            if(matrix.empty()) return false;
            
            int row = matrix.size();
            int rowA=0; int rowB = row-1; 
            int rowMid=0;
            int searchRow;
            while(rowA<rowB){
                rowMid = (rowA+rowB)/2;
                if(target<matrix[rowMid][0]){
                    if(rowMid-1<0) return false;
                    else if(target>=matrix[rowMid-1][0]){searchRow=rowMid-1;break;}
                    else rowB=rowMid-2;
                }else{
                    if(target<matrix[rowMid+1][0]){searchRow=rowMid;break;}
                    else rowA=rowMid+1;
                }
            }
            if(rowA==rowB) searchRow = rowA;
            
            int col = matrix[0].size();
            int colA=0; int colB=col-1;
            int colMid=0;
            if(target<matrix[searchRow][colA] || target>matrix[searchRow][colB]) return false;
            while(colA<=colB){
                colMid = (colA+colB)/2;
                if(target==matrix[searchRow][colMid]) return true;
                if(target<matrix[searchRow][colMid]) colB=colMid-1;
                else colA=colMid+1;
            }
            return false;
        }
    };
  • 相关阅读:
    pm2中文文档
    大前端技能图谱
    手把手教你用express搭建个人博客(二)
    javascript this讲解
    手把手教你用express搭建个人博客(一)
    使用国内手机号注册Google帐号的方法(2020-12-13亲测有效)
    常见浏览器修改User-Agent的方法
    Debian 9 Stretch国内常用镜像源
    Nginx核心模块内置变量
    tmux基本操作
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4333325.html
Copyright © 2011-2022 走看看