Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II)

Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II)


编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例:

现有矩阵 matrix 如下:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

给定 target = 5,返回 true

给定 target = 20,返回 false


在二维矩阵中找target,那既然这题在二分法专题中,我们用二分法做。

取每一行出来,进行二分,找到了返回true,找不到就搜索下一行。

AC代码:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length==0 || matrix==null) return false;
        
        for(int i=0;i<matrix.length;i++){
            int[] temp = matrix[i];
            if(temp.length==0 || temp==null) return false;
            if(binarySearch(temp,0,temp.length-1,target)){
                return true;
            }
        }
        return false;
    }

    private boolean binarySearch(int[] nums, int L, int R, int target) {
        
        while(L<R){
            int mid = (L+R)>>>1;
            if(nums[mid]==target){
                return true;
            }else if(nums[mid]>target){
                R = mid-1;
            }else{
                L = mid+1;
            }
        }
        if(nums[L]==target) return true;
        
        return false;
    }
}

猜你喜欢

转载自www.cnblogs.com/qinyuguan/p/11410210.html