Leetcode——二维数组/矩阵中的查找

Posted Yawn,

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode——二维数组/矩阵中的查找相关的知识,希望对你有一定的参考价值。

1.题目

2. 题解

(1)暴力

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
    
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == target) {
                    return true;
                }
            }
        }

        return false;
    }
}

(2)转为二叉树

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
		 // 以左下角的数字为准,跟target比较,决定是排除列还是行
        int i = matrix.length - 1;
        int j = 0;                  //i为行,j为列
        
        while(i >= 0 && j < matrix[0].length){
            if(matrix[i][j] > target)		//matrix[i][j]为该行最小值还大于target,排除该行
                i--;
            else if(matrix[i][j] < target)	//matrix[i][j]为该列最大值还小于target,排除该列
                j++;
            else    
                return true;
        }
        return false;
    }
}

以上是关于Leetcode——二维数组/矩阵中的查找的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode74. 搜索二维矩阵

LeetCode | 面试题04. 二维数组中的查找剑指OfferEasyPython数组

[LeetCode]剑指 Offer 04. 二维数组中的查找

[LeetCode]剑指 Offer 04. 二维数组中的查找

LeetCode74. 搜索二维矩阵

Leetcode刷题Python剑指 Offer 04. 二维数组中的查找