力扣练习之搜索二维矩阵 II

我爱海鲸 2023-04-06 17:22:52 力扣、中级算法

简介中级算法、排序和搜索

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvc64r/

解法一:(python)

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

思路:就是从二维数组的左下角开始遍历,如果目标值大于当前值就向左移动一个位置,如果目标值小于当前值就向上移动一个位置。

你好:我的2025