zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):074-Search a 2D Matrix


    题目来源


    https://leetcode.com/problems/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.

    题意分析


    Input:  a matrix and a target to query

    Output: True or False

    Conditions:在矩阵中查找元素,注意矩阵是有序的


    题目思路


    先在列二分查找定位哪一列,然后再行二分查找,注意边界条件

    PS:其实直接在列查找的时候,发现low-1小于0时,直接返回False就可以了,但是所贴代码可以移植到插入元素的二分排序里面,为了统一就没有改动了。


    AC代码(Python)


     1 __author__ = 'YE'
     2 
     3 class Solution(object):
     4     def searchMatrix(self, matrix, target):
     5         """
     6         :type matrix: List[List[int]]
     7         :type target: int
     8         :rtype: bool
     9         """
    10         m = len(matrix)
    11         n = len(matrix[0])
    12         low = 0
    13         high = m - 1
    14 
    15         while low <= high:
    16             mid = (low + high) / 2
    17             if matrix[mid][0] == target:
    18                 return True
    19             elif matrix[mid][0] > target:
    20                 high = mid - 1
    21             else:
    22                 low = mid + 1
    23         row = low - 1
    24         if row < 0:
    25             row = 0
    26 
    27         low = 0
    28         high = n - 1
    29 
    30         while low <= high:
    31             mid = (low + high) / 2
    32             if matrix[row][mid] == target:
    33                 return True
    34             elif matrix[row][mid] > target:
    35                 high = mid - 1
    36             else:
    37                 low = mid + 1
    38         return False
    39 
    40 matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]
    41 target = 16
    42 print(Solution().searchMatrix(matrix,target))
  • 相关阅读:
    win 8.1右键引起资源管理器重启
    lodash学习笔记之Array方法
    window下Ionic环境安装
    Ionic angular-ui-router小案例
    NPOI SetColumnHidden隐藏列不起作用的原因
    关于js隐式转换的有趣例子
    oracle中between and闭合性
    Javascript有那些奇技淫巧?
    PowerDesigner逆向工程连接服务器端oracle过程
    openlayers 添加 arcgis rest feature server 使用 vue cli+jsonp
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5097431.html
Copyright © 2011-2022 走看看