leetcode 240. 搜索二维矩阵 II

2023.11.22

leetcode 240. 搜索二维矩阵 II_第1张图片

        本题最先想到的是暴力法和二分法,暴力法就不写了,写一下二分法的解法,java代码如下:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for(int[] row : matrix){
            int left = 0;
            int right = row.length-1;
            while(left <= right){
                int mid = (left + right) / 2;
                if(row[mid] == target) return true;
                else if(row[mid] > target) right = mid-1;
                else left = mid + 1; 
            }
        }
        return false;
    }
}

        翻看了下评论区,有个Z字型解法,是从右上角开始遍历,我则从左下角开始遍历,然后当前元素大于target值就往上走,小于target值就往右走,直到走到边界也没找到就返回false,java代码如下:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length-1;
        int col = 0;
        //从左下角开始搜索
        while(row>=0 && col target) row--;
            else col++;
        }
        return false;
    }
}

你可能感兴趣的:(leetcode专栏,leetcode,矩阵,算法,java)