13. LeetCode 240. 搜索二维矩阵 II

LeetCode 240. 搜索二维矩阵 II

天津科技大学第六届科技文化节算法设计大赛第13题
难度:中等

题目:

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

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

示例 1:
13. LeetCode 240. 搜索二维矩阵 II_第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:
13. LeetCode 240. 搜索二维矩阵 II_第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
-109 <= matrix[i][j] <= 109
每行的所有元素从左到右升序排列
每列的所有元素从上到下升序排列
-109 <= target <= 109

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

  1. 解法一:遍历就完了
  2. 解法二:由于矩阵是以一定规律排列的,因此可以使用和二分查找类似的搜索方法,和扫雷类似,及时排除掉不可能的位置,减少搜索时间,这里不再赘述。

源代码

    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for i in matrix:
            for j in i:
                if j==target:
                    return True
        return False

结果

13. LeetCode 240. 搜索二维矩阵 II_第3张图片
13. LeetCode 240. 搜索二维矩阵 II_第4张图片

你可能感兴趣的:(算法,LeetCode,矩阵,leetcode,算法)