4. 二维数组中的查找(剑指 Offer 题解Java版)

4. 二维数组中的查找

题目链接

牛客网

题目描述

给定一个二维数组,其每一行从左到右递增排序,从上到下也是递增排序。给定一个数,判断这个数是否在该二维数组中。

Consider the following 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]
]

Given target = 5, return true.
Given target = 20, return false.
Copy to clipboardErrorCopied

解题思路

要求时间复杂度 O(M + N),空间复杂度 O(1)。其中 M 为行数,N 为 列数。

该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。
在这里插入图片描述

package 二维数组中的查找;/*
作者     :XiangLin
创建时间 :18/02/2020 11:51
文件     :FindTarget.java
IDE      :IntelliJ IDEA
*/

public class FindTarget {
    public boolean Find(int tareget,int[][] martix){
        if(martix == null || martix.length == 0 || martix[0].length == 0)   //判断二维数组是否存在
            return false;
        int rows = martix.length,cols = martix[0].length; //求出二维数组列和行的长度
        int r = 0,c = cols - 1;     //初始状态定位到二维数组的右上角
        while (r < rows - 1 && c >= 0){
            if (tareget == martix[r][c])  //找到目标值的情况
                return true;
            else if(tareget > martix[r][c])   //目标值比当前大,说明行要增加,往下走
                r ++;
            else   //目标值比当前小,说明列要减小,往左走
                c --;
        }
        return false;
    }

    public static void main(String[] args) {
        FindTarget find = new FindTarget();
        int[][] martix  = {
                {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}
        };
        int target = 0;
        boolean x = find.Find(target,martix);
        System.out.println(x);

    }
}

输出:
false

It is love that will heal you. It’s what heals us all.
爱会治愈你,会治愈我们所有人。

XiangLin
2020年2月18日于重庆城口
好好学习,天天向上,终有所获

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值