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

    题目来源:

      https://leetcode.com/problems/search-a-2d-matrix/


    题意分析:

      给一个m×n矩阵,矩阵是按照从小到大排列,也就是a[i][j]和a[m][n]如果i  > m则a[i][j]>a[m][n],如果i == m,j > n,则a[i][j]>a[m][n]。


    题目思路:

      利用二分查找,首先确定在那个行,然后继续二分查找。


    代码(Python):

     1 class Solution(object):
     2     def searchMatrix(self, matrix, target):
     3         """
     4         :type matrix: List[List[int]]
     5         :type target: int
     6         :rtype: bool
     7         """
     8         m = len(matrix)
     9         if m == 0:
    10             return False
    11         n = len(matrix[0])
    12         if n == 0:
    13             return False
    14         mfirst,mlast = 0,m - 1
    15         while mfirst < mlast:
    16             mid = (mfirst + mlast + 1) // 2
    17             if matrix[mid][0] == target:
    18                 return True
    19             if matrix[mid][0] < target:
    20                 mfirst = mid
    21             else:
    22                 mlast = mid - 1
    23         print(mfirst)
    24         nfirst,nlast = 0,n - 1
    25         while nfirst <= nlast:
    26             mid = (nfirst + nlast) // 2
    27             if matrix[mfirst][mid] == target:
    28                 return True
    29             if matrix[mfirst][mid] < target:
    30                 nfirst = mid + 1
    31             else:
    32                 nlast = mid - 1
    33         return False
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/5069802.html

  • 相关阅读:
    ElasticSearch查询多条件同时满足时返回所需数据
    Linux环境下安装ElasticSearch
    微博抓取照片视频
    numpy 常用方式
    Centos最小化安装 AWVS 的坑
    使用centos安装nessus 8.15,并解除IP限制
    Linux CentOS7 开通端口外网端口访问权限
    VSCode配置C语言环境
    Python MySQL
    web7
  • 原文地址:https://www.cnblogs.com/chruny/p/5069802.html
Copyright © 2011-2022 走看看