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
    
  • 相关阅读:
    hdu 1042 N!
    hdu 1002 A + B Problem II
    c++大数模板
    hdu 1004 Let the Balloon Rise
    hdu 4027 Can you answer these queries?
    poj 2823 Sliding Window
    hdu 3074 Multiply game
    hdu 1394 Minimum Inversion Number
    hdu 5199 Gunner
    九度oj 1521 二叉树的镜像
  • 原文地址:https://www.cnblogs.com/absolute/p/5678008.html
Copyright © 2011-2022 走看看