zoukankan      html  css  js  c++  java
  • leetcode74

     1 import bisect
     2 class Solution:
     3     def searchMatrix(self, matrix: 'List[List[int]]', target: int) -> bool:
     4         rows = len(matrix)
     5         if rows == 0:
     6             return False
     7         columns = len(matrix[0])
     8         if columns == 0:
     9             return False
    10         rowlist = []
    11         for i in range(rows):
    12             rowlist.append(matrix[i][0])
    13         
    14         rownum = bisect.bisect_left(rowlist, target)
    15 
    16         if rownum >= rows:#比最后一行的第一个元素要大
    17             rownum -= 1#在最后一行查询
    18         elif rownum > 0:#在第一行和最后一行之间
    19             if rowlist[rownum] == target:#第一个元素就是所查询的值,直接返回
    20                 return True
    21             else:
    22                 rownum -= 1#在前一行查询
    23         else:#rownum == 0
    24             if rowlist[rownum] == target:#比第一行的第一个元素要小
    25                 return True
    26         collist = matrix[rownum]
    27         idx = bisect.bisect_left(collist, target)
    28         if idx >= columns:
    29             return False
    30         return collist[idx] == target

    先按照列进行二分查找,找到符合的行,再对这一行进行二分查找。

  • 相关阅读:
    Python 写文件
    Python 读文件
    Python 打开文件(File Open)
    Python 异常处理(Try...Except)
    Python PIP包管理器
    Python 正则表达式(RegEx)
    Python JSON
    Python 模块
    Python 迭代器(Iterator)
    Python 继承
  • 原文地址:https://www.cnblogs.com/asenyang/p/12015184.html
Copyright © 2011-2022 走看看