[Leetcode] 240. Search a 2D Matrix II

本文提供了一种解决LeetCode上Search a 2D Matrix II问题的有效算法。该算法利用了矩阵的特性,通过从逆对角线的两端开始搜索,实现了高效查找目标值的功能。适用于所有类型的二维矩阵搜索问题。

Problems:
https://leetcode.com/problems/search-a-2d-matrix-ii/

Solution:
鉴于matrix的特性,binary search已经不适用,为了迭代方便,从逆对角线的两端下手(任意选一端即可)

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0 || matrix == null) {
            return false;
        }
        // 此处选的是逆对角线的下端
        // 由于matrix的特性,可以将搜索简化成两条线:大于target则向右搜索,小于target则向左搜索
        // 对角线两端不适用的原因在于,从起点开始target只存在大于/小于的情况
        int m = matrix.length, n = matrix[0].length;
        int curRow = m-1, curCol = 0;
        while (curRow >= 0 && curCol < n) {
            if(matrix[curRow][curCol] == target) {
                return true;
            } else if (matrix[curRow][curCol] < target) {
                curCol++;
            } else {
                curRow--;
            }
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值