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.

    这题很简单

    思路:二分法确定target可能在第几行出现。再用二分法在该行确定target可能出现的位置。时间复杂度O(logn+logm)

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            int m=matrix.size();
            int n=matrix[0].size();
            int l=0,r=m-1,mid;
            if(target>matrix[m-1][n-1]||target<matrix[0][0])
                return false;
            while(l<r)
            {
                mid=l+(r-l)/2;
                if(target==matrix[mid][n-1])
                    return true;
                else if(target<matrix[mid][n-1])
                    r=mid;
                else 
                    l=mid+1;
            }
            int index=r;
            l=0;
            r=n-1;
            while(l<=r)
            {
                mid=l+(r-l)/2;
                if(target==matrix[index][mid])
                    return true;
                else if(target<matrix[index][mid])
                    r=mid-1;
                else 
                    l=mid+1;
            }
            return false;
        }
    };
  • 相关阅读:
    装配Bean
    百练
    东软小选拔
    俄罗斯乘法
    POJ
    ACdream
    javascript 链式作用域
    ie6/7 bug
    onreadystatechange 和 status
    瀑布流 <<转>>
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4580196.html
Copyright © 2011-2022 走看看