[BinarySearch]074 Search a 2D Matrix

  • 分类:BinarySearch

  • 考察知识点:BinarySearch

  • 最优解时间复杂度:O(log(n+m))原版/O(logn)改进版

  • 最优解空间复杂度:O(1)

74. 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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

代码:

BinarySearch方法1:

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix)==0 or len(matrix[0])==0 or matrix[0][0]>target or matrix[-1][-1]<target:
            return False

        list_new=[]
        for each in matrix:
            list_new+=each
        start=0
        end=len(list_new)-1
        while end-start>1:
            mid=(end-start)//2+start
            if target==list_new[mid]:
                return True
            elif target<list_new[mid]:
                end=mid
            else:
                start=mid

        if list_new[start]==target:
            return True
        if list_new[end]==target:
            return True
        return False

BinarySearch方法2改进版:

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix)==0 or len(matrix[0])==0 or matrix[0][0]>target or matrix[-1][-1]<target:
            return False

        row=len(matrix)-1
        while(matrix[row][0]>target):
            row-=1

        start=0
        end=len(matrix[row])-1
        while(end-start)>1:
            mid=(end-start)//2+start
            if matrix[row][mid]==target:
                return True
            elif matrix[row][mid]<target:
                start=mid
            else:
                end=mid
        if matrix[row][start]==target or matrix[row][end]==target:
            return True

        return False

讨论:

1.排序的,然后找数字,一看到这两个条件,那么肯定是用binary search!切记切记
2.改进的方法先判断每一行是否是比原来的大,然后再每一小行做BinarySearch就可以了

我真牛逼啊哈哈!
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,872评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,930评论 0 13
  • 这一届的世界杯让许多人始料不及,我也是其中的一员。虽说自己也算不上是什么铁杆足球粉,但对足球还是有一定的关注,对一...
    kou爺阅读 147评论 0 1
  • “这是我说的最后一 句话。” 小女孩用食指在紧闭的嘴唇上划了一下,模拟着拉上拉链的动作。 刚才在海洋公园里看海豚表...
    平方田阅读 310评论 1 1
  • 小学一年级的时候,奶奶去世了。关于奶奶的记忆并不多,但是记得奶奶很疼我们姐弟三个。好像所有人的奶奶都是很疼...
    阳槐阅读 250评论 0 1

友情链接更多精彩内容