zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 24-1

    Search a 2D Matrix

    考点:方法很简单,对第0列和之后找到的行做两次2分,重点是用第一次二分后low和high的位置来确定行。对于二分没找到的情况:low这时候比high大1,low对应的是>target的元素,high对应的是<target的元素。对于这题,我们需要用high,因为行也是递增的。

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            m = len(matrix)
            n = len(matrix[0])
            low,high = 0,m-1
            while low<=high:
                mid = low + (high-low)/2
                if matrix[mid][0]==target:
                    return True
                elif matrix[mid][0]>target:
                    high=mid-1
                else:
                    low=mid+1
            print high
            if high>=0 and high<m:
                row = high
                low,high = 0,n-1
                while low<=high:
                    mid = low+(high-low)/2
                    print mid
                    if matrix[row][mid]==target:
                        return True
                    elif matrix[row][mid]>target:
                        high=mid-1
                    else:
                        low=mid+1
                    
            return False
    
  • 相关阅读:
    装饰复杂函数
    装饰器01
    闭包
    函数的嵌套定义
    名称空间
    函数的嵌套调用
    函数的对象
    形参
    实参
    形参与实参
  • 原文地址:https://www.cnblogs.com/absolute/p/5678008.html
Copyright © 2011-2022 走看看