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

Posted qinyuguan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    

 

以上是关于Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II)的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 240. 搜索二维矩阵 II ☆☆☆(二分查找类似)

LeetCode每日一题:240搜索二维矩阵II

leetcode打卡--240. 搜索二维矩阵 II

Leetcode练习(Python):二分查找类:第240题:搜索二维矩阵 II:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 ta

Leetcode练习(Python):二分查找类:第240题:搜索二维矩阵 II:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 ta

5-005-(LeetCode- 240) 搜索二维矩阵 II