每日一练_100(2021.9.17) 搜索二维矩阵。

本文介绍了一种高效的搜索算法,用于在一维表示的二维矩阵中查找目标值。该矩阵的特点是每一行从左到右单调递增,且每一行的第一个整数大于前一行的最后一个整数。通过将矩阵转化为一维数组并使用二分查找,可以在O(log n)的时间复杂度内完成搜索。

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/sou-suo-er-wei-ju-zhen-by-leetcode-solut-vxui/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

个人微改:

class matrix{
    public boolean searchMatrix(int[][] matrix,int target) {
        int m = matrix.length,n=matrix[0].length;
        int low=0,high=m*n-1;
        while(low<=high) {
            int mid = (high-low)/2+low;
            int x = matrix[mid/n][mid%n];
            if(x>target) {
                high=mid-1;
            }else if(x<target) {
                low=mid+1;
            }else {
                return true;
            }
        }
        return false;
    }
}
public class Search_A_2D_Matrix {
    public static void main(String args[]) {
        matrix hah = new matrix();
        int[][] a = new int[][] {{1,3,5,7},{10,11,16,20},{23,30,34,60}};
        System.out.println(hah.searchMatrix(a,3));
        System.out.println(hah.searchMatrix(a,13));
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值