LeetCode-240. 搜索二维矩阵 II【数组 二分查找 分治 矩阵】

LeetCode-240. 搜索二维矩阵 II【数组 二分查找 分治 矩阵】

题目描述:

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

每行的元素从左到右升序排列。

每列的元素从上到下升序排列。

示例 1:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5

输出:true

示例 2:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20

输出:false

提示:

m == matrix.length

n == matrix[i].length

1 <= n, m <= 300

-10^9^ <= matrix[i][j] <= 10^9^

每行的所有元素从左到右升序排列

每列的所有元素从上到下升序排列

-10^9^ <= target <= 10^9^

解题思路一:从左下角或者右上角元素出发,来寻找target。

如下图所示,我们将矩阵逆时针旋转 45° ,并将其转化为图形式,发现其类似于 二叉搜索树 ,即对于每个元素,其左分支元素更小、右分支元素更大。因此,通过从 "根节点" 开始搜索,遇到比 target 大的元素就向左,反之向右,即可找到目标值 target 。

"根节点" 对应的是矩阵的 "左下角" 和 "右上角" 元素,本文称之为 标志数 ,以 matrix 中的 左下角元素 为标志数 flag ,则有:

  1. 若 flag > target ,则 target 一定在 flag 所在 行的上方 ,即 flag 所在行可被消去。
  2. 若 flag < target ,则 target 一定在 flag 所在 列的右方 ,即 flag 所在列可被消去。

"右上角" 元素 也是类似

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        i, j = len(matrix) - 1, 0
        while i >= 0 and j < len(matrix[0]):
            if matrix[i][j] > target: 
                i -= 1
            elif matrix[i][j] < target:
                j += 1
            else:
                return True
        return False

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

空间复杂度:O(1)

解题思路二:右上角元素,代码

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        i, j = 0, len(matrix[0]) - 1
        while i < len(matrix) and j >= 0:
            if matrix[i][j] > target:
                j -= 1
            elif matrix[i][j] < target:
                i += 1
            else:
                return True
        return False

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

空间复杂度:O(1)

解题思路三:暴力也能过

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
            for element in row:
                if element == target:
                    return True
        return False

时间复杂度:O(nm)

空间复杂度:O(1)

解题思路四:二分查找

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
            idx = bisect.bisect_left(row, target)
            if idx < len(row) and row[idx] == target:
                return True
        return False

时间复杂度:O(mlogn)

空间复杂度:O(1)

相关推荐
OTWOL28 分钟前
【C++编程入门基础(一)】
c++·算法
谏君之34 分钟前
C语言实现的常见算法示例
c语言·算法·排序算法
机器视觉知识推荐、就业指导1 小时前
【数字图像处理二】图像增强与空域处理
图像处理·人工智能·经验分享·算法·计算机视觉
IT猿手2 小时前
超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
人工智能·算法·机器学习·matlab·无人机
Erik_LinX2 小时前
算法日记25:01背包(DFS->记忆化搜索->倒叙DP->顺序DP->空间优化)
算法·深度优先
Alidme2 小时前
cs106x-lecture14(Autumn 2017)-SPL实现
c++·学习·算法·codestepbystep·cs106x
小王努力学编程2 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
最遥远的瞬间2 小时前
15-贪心算法
算法·贪心算法
维齐洛波奇特利(male)3 小时前
(动态规划 完全背包 **)leetcode279完全平方数
算法·动态规划
项目申报小狂人5 小时前
改进收敛因子和比例权重的灰狼优化算法【期刊论文完美复现】(Matlab代码实现)
开发语言·算法·matlab