• [ 剑指offer ] 面试题4:二维数组中的查找


    题目描述


    编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

    • 每行中的整数从左到右按升序排列。
    • 每行的第一个整数大于前一行的最后一个整数。

    示例 1:

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

    示例 2:

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

    解题思路 


    1.暴力解法

    略...

    2.利用行递增,列递增的特性,从右上角开始排除一行或者一列

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if matrix ==[]:
                return False
            row,col = len(matrix),len(matrix[0])
            x,y=0,col-1
            while x<row and y>=0:
                if target < matrix[x][y]:
                    y-=1
                elif target > matrix[x][y]:
                    x+=1
                else:
                    return True
            return False

    3.类似2,只通过排除行来解题。

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            for i in matrix:
                try:
                    if target <= i[-1]:
                        for j in i:
                            if target == j:
                                return True
                except:
                    return False
            return False

    4.根据题意,二维数组在一维上是递增的,这样就可以用二分查找来解题

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if matrix == [] :
                return False
            m,n = len(matrix),len(matrix[0])
            left,right = 0,m*n-1
            while left<=right:
                mid = (left + right) // 2
                # 提问:二维数组一维化后,要判断下标为mid的值,如何将一维数组中的坐标转换成二维数组的坐标呢?
                # 答:如下
                x,y = mid//n , mid%n
                if target < matrix[x][y]:
                    right = mid - 1
                elif target > matrix[x][y]:
                    left = mid + 1
                elif target == matrix[x][y]:
                    return True
            return False

     

    总结


     1.二分查找中,要注意while循环的临界值,left==right

    2.二分查找中,重点在于如何将一维数组的坐标映射到二维数组的真实坐标。

  • 相关阅读:
    Python自动化开发从浅入深-进阶(Twisted、Reactor)
    Python自动化开发从浅入深-进阶(socketServer)
    Python自动化开发从浅入深-进阶(select,poll,epoll学习)
    Python自动化开发从浅入深-进阶(进程)
    Python自动化开发从浅入深-语言基础(一些心得)
    Python自动化开发从浅入深-语言基础(常用模块)
    PSSH 批量管理服务器
    linux常用命令大全
    Why is 0[0] syntactically valid in javascript?
    免费为王(一)
  • 原文地址:https://www.cnblogs.com/remly/p/12290351.html
Copyright © 2020-2023  润新知