LeetCode每日一题之二维数组中的查找

这篇博客介绍了如何解决LeetCode的一道题目,即在一个按特定顺序排列的二维数组中查找目标整数。提供了两种解法,一种是遍历所有元素,另一种是通过逐级比较优化搜索效率。通过这种方法,可以有效地在有序的二维数组中找到目标值,提高搜索效率。
摘要由CSDN通过智能技术生成

LeetCode每日一题之整数反转

在一个二维数组array中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
[
[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]
]

给定target=7,返回true
给定target=3,返回false

思路

1、这道题核心就在于设置两个索引,实现对行和列中元素的定位
2、一方面可以暴力解法,遍历数组中的全部元素
3、另一方面可以取巧一些,通过逐级比较大小,来确定行索引的移动,还是列索引的移动,得到最终值

解法:

方法一:遍历全部元素

public class Solution {
    public static void main(String[] args) {
        int[][] arr = {{1, 2, 8, 9},
                {2, 4, 9, 12},
                {4, 7, 10, 13},
                {6, 8, 11, 15}};
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        System.out.println(searchArray1(arr, x));
    }

    public static boolean searchArray1(int[][] array, int target) {
        if (array == null || array.length == 0 || array[0] == null || array[0].length == 0) {
            return false;
        }
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                if (array[i][j] == target) {
                        return true;
                    }
            }
        }
        return false;
    }
}

方法二:逐级优化比较

public class Solution {
    public static void main(String[] args) {
        int[][] arr = {
                {1, 2, 8, 9},
                {2, 4, 9, 12},
                {4, 7, 10, 13},
                {6, 8, 11, 15}};
        Scanner sc=new Scanner(System.in);
        int x=sc.nextInt();
        System.out.println(searchArray(arr, x));
    }

    public static boolean searchArray(int[][] array, int target) {
        if(array == null || array.length == 0 || array[0] == null || array[0].length == 0){
            return false;
        }
        int row = array.length;
        //确定有几行
        int column = array[0].length;
        //确定数组有几列
        int down = 0;
        //设置一个列索引完成定位坐标的上下移动
        int right = column - 1;
        //同上,完成左右移动
        while(down<row&&right>=0){
            //限制索引,使其不发生越界 down<row 即down不能超过总行数; right<column-1 ,即这个索引是从右往左指向,从大到小指向。逐渐缩小范围
            if(array[down][right] == target){
                return true;
            }
            if(array[down][right] > target){
                right--;
            }else{
                down++;
            }
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值