Skip to content

Latest commit

 

History

History
71 lines (48 loc) · 1.26 KB

排序矩阵查找.md

File metadata and controls

71 lines (48 loc) · 1.26 KB

面试题 10.09. 排序矩阵查找

https://leetcode-cn.com/problems/sorted-matrix-search-lcci/

题目描述

给定M×N矩阵,每一行、每一列都按升序排列,请编写代码找出某元素。

示例:

现有矩阵 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。

给定 target = 20,返回 false。

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

思路

从左下角开始搜索

python代码

执行用时: 40 ms , 在所有 Python3 提交中击败了 93.29% 的用户 内存消耗: 19.4 MB , 在所有 Python3 提交中击败了 27.16% 的用户


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):#如果当前位置大于target
                i-=1
            elif(matrix[i][j]==target):
                return True
            else:
                j+=1
        return False