LeetCode:240搜索二维矩阵Ⅱ

java 复制代码
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }

        int m = matrix.length;
        int n = matrix[0].length;
        //初始搜索位置
        int row = 0;
        int col = n -1;
        //在矩阵中搜索
        while(row < m && col >= 0){
            if(matrix[row][col] > target){
                col--;
            }else if(matrix[row][col] < target){
                row++;
            }else if(matrix[row][col] == target){
                return true;
            }
        }
        return false;
    }
}

解题思路:从右上角开始找,可以将这个矩阵看作是一个二叉搜索树,往左走小于该节点,往下走大于该节点。

相关推荐
kingx36 小时前
Bugku 逆向 MatrixHunter:黑盒 oracle + GF(2) 消元出唯一解
网络安全·矩阵·逆向·ctf
likexuec1 天前
数据结构(2)
数据结构
文丑颜不良啊1 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z1 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH1 天前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶1 天前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊1 天前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!2 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊2 天前
算法之双指针系列(一)
算法·leetcode