LeetCode第74题,搜索二维矩阵,Java,二分查找

问题:

LeetCode第74题,搜索二维矩阵,Java,二分查找_第1张图片

思路:

第一种思路是,把所有的拼起来就是一个数组嘛,然后用二分法就了

第二种思路是,先看第一列的,用二分查找,找到合适的行,然后再用二分查找,对应的一行

第二种的思路还是,把自己的东西分区域,然后分别分析每个部分的情况,就是容易漏掉某些状态

代码:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        //先看第一列,再锁定行元素
        int left = 0;
        int right = m-1;
        if(matrix.length==1){
            return scanrow(matrix[0],target);
        }
        while(left<=right){
            int mid = left+ (right-left)/2;
            if(mid == 0){
                if(target < matrix[mid][0]){
                    return false;
                }else if(target>=matrix[mid][0]&& target= matrix[mid+1][0]){
                    left = mid+1;
                }
            }else if(mid == matrix.length-1 ){
                return scanrow(matrix[mid],target);
            }else if(mid != 0&& mid != matrix.length-1){
                if(target >= matrix[mid][0]&&target= matrix[mid-1][0]){
                    return scanrow(matrix[mid-1],target);
                }
                else if(target >= matrix[mid+1][0]){
                    left = mid+1;
                }else if(target <= matrix[mid-1][0]){
                    right = mid-1;
                }
            }
        }
        return false;

    }

    public boolean scanrow(int[] row, int target){
        int left = 0;
        int right= row.length-1;

        while(left<=right){
            int mid = left + (right-left)/2;
            if(row[mid] == target){
                return true;
            }else if(row[mid]>target){
                right = mid-1;
            }else if(row[mid]

第一种方法的思路就比较简单了,速度照样很快

代码:

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

        int left = 0;
        int right = m*n-1;

        while(left<=right){
            int mid = left + (right-left)/2;
            if(matrix[mid/n][mid%n] == target){
                return true;
            }else if(matrix[mid/n][mid%n] > target){
                right = mid - 1;
            }else if(matrix[mid/n][mid%n] < target){
                left = mid + 1;
            }
        }
        return false;
        
    }

}

 

你可能感兴趣的:(代码打卡,java,leetcode,二分查找,矩阵)