leetcode 热题 100_搜索二维矩阵

题解一:

二叉搜索树:从矩阵右上角观察,结构类似二叉搜索树,因此可以用类似的解法来做。具体做法是双指针从右上角开始,向左下角逐步搜索,如果当前值比目标值大,则向下移动,如果当前值比目标值小,则向左移动。直到找到目标值或指针出界。

java 复制代码
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;

        for (int i = 0, j = n - 1; i < m && j >= 0; ) {
            if (matrix[i][j] > target) j--;
            else if (matrix[i][j] < target) i++;
            else if (matrix[i][j] == target) return true;
        }
        return false;
    }
}
相关推荐
zander2587 分钟前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲23 分钟前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力5541 分钟前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜1 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者1 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂1 小时前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_1 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.2 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks2 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路2 小时前
算法8.环形队列
算法