Leetcode 74. Search a 2D Matrix 2D矩阵查找 解题报告

本文介绍了一种在已排序的二维数组中高效查找目标值的方法,通过先在第一列进行二分查找确定所在行,再在该行内进行常规二分查找实现目标值的定位。

1 解题思想

通常来说,我们习惯在一个一维数组中做查找,那么当我们在二维数组当中查找,又该怎么做呢?

这道题就是让我们在一个二维数组中进行查找,当然这是一个已经排好序的数组了。每一行的数据都是递增的,每一列的数据也是递增的,下一行的第一个数据肯定比上一行的最后一个大。总之你可以看成是已经排好序的数组,折叠到一个二维数组当中。

其实解题方式也很简单:
1、首先查找所在行,即使用每行的第一个元素,进行二分查找,找到小于等于目标值当中的最大的哪一行。

2、在那一行之间,使用正常的二分查找。

2 原题

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.

3 AC解

public class Solution {
    //其实就是两个二分法查找,首先在第一列做二分查找,找到行的位置(当前的行的第一个值小于target,但是下一行大于),再在行内做标准二分查找

    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length==0)
            return false;
        int top=0,bottom=matrix.length-1;
        int left=0,right=matrix[0].length-1;
        int mid;
        //首先列内查找,寻找起始在第几行,这个二分的目的就只是要找出小于等于的那个位置。。。。
        while(top<bottom){
            mid=(top+bottom+1)/2;
            if(matrix[mid][0]==target)
                return true;
            if(matrix[mid][0]>target)
                bottom=mid-1;
            else top=mid;
        }
        //System.out.println(top);
        //然后做行内的差距,这个二分法是正常的做法
        while(left<=right){
            mid=(left+right)/2;
            if(matrix[top][mid]==target)
                return true;
            if(matrix[top][mid]>target)
                right=mid-1;
            else left=mid+1;
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值