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;
        }
    };
  • 相关阅读:
    oracle函数 exp(y)
    oracle函数 power(x,y)
    oracle函数 floor(x)
    oracle函数 ceil(x)
    oracle函数 ABS(x)
    简明Python3教程(A Byte of Python 3)
    C#实现窗口最小化到系统托盘
    简明Python3教程 4.安装
    ubuntu
    Javascript 笔记与总结(2-6)var
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4333325.html
Copyright © 2011-2022 走看看