不为成仙,只为在这红尘中等你回来。

您现在的位置是:网站首页>>LeetCode

74.Search a 2D Matrix [Medium] [Array | Binary Search]

2020年11月7日 16:28 | 分类:LeetCode | 标签: Python LeetCode Array Binary Search

题意

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 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:

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

Example 2:

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

Example 3:

输入:matrix = [], target = 0
输出:false

Note:

  • m == matrix.length
  • n == matrix[i].length
  • 0 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

思路

用二分查找,重点是找到 mid 在第几行第几列。也可以遍历每一行,然后再行内做二分查找,当然效率会差点。

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix or not matrix[0]:
            return False
        m, n = len(matrix), len(matrix[0])
        left = 0
        right = m * n - 1
        while left <= right:
            mid = (left + right) // 2
            i = mid // n
            j = mid % n
            if matrix[i][j] > target:
                right = mid - 1
            elif matrix[i][j] < target:
                left = mid + 1
            else:
                return True
        return False