[LeetCode] 74. 搜索二维矩阵

题目链接 : https://leetcode-cn.com/problems/search-a-2d-matrix/

题目描述:

编写一个高效的算法来判断 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

思路:

一句话解释: 二维数组转一维,用二分法

详细解释,

二维变成一维,就是按照二维数组顺序,依次变成一维数列,所以有如果一个数在一维坐标位置是loc,那么它在二维坐标就是[loc/col][loc%col]

时间复杂度: (O(log(mn)) = O(log(m) + log(n)))

代码:

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix: return False
        row = len(matrix)
        col = len(matrix[0])
        left = 0
        right = row * col
        while left < right:
            mid = left + (right - left) // 2
            if matrix[mid // col][mid % col] < target:
                left = mid + 1
            else:
                right = mid
        #print(left,right)
        return left < row * col and matrix[left // col][left % col] == target

java

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int row = matrix.length;
        int col = matrix[0].length;
        int left = 0;
        int right = row * col;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (matrix[mid / col][mid % col] < target) left = mid + 1;
            else right = mid;
        }
        return (left < row * col && matrix[left / col][left % col] == target); 
    }
}
原文地址:https://www.cnblogs.com/powercai/p/10950399.html