算法:特殊二维数组查询key值是否存在

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

思路:
{1, 3, 6, 9},
{2, 5, 7, 12},
{6, 10, 14, 18},
{8, 11, 15, 20}};
行:从上到下递增,列:从左到右递增
选择右上角9位置为参照,如key=9返回找到;如果key<9,列左移一个单位,还是比6小,列继续左移,即cum–;如果key>9,行向下移动一个单位,同理row++;

Java实现

public class ArrayFindKey {
    public static void main(String[] args) {
        int[][] arr = {
                {1, 3, 6, 9},
                {2, 5, 7, 12},
                {6, 10, 14, 18},
                {8, 11, 15, 20}};
        int key = 6;

        System.out.println( findKey(arr, key));
    }

    /**
     * 从右上角开始,如果key,等于该值返回,小于该值,cums左移一个单位,如果大于该值rows下移一个单位
     *
     * @param arr
     * @param key
     */
    private static boolean findKey(int[][] arr, int key) {
        int rows = 0;
        int cums = arr[0].length - 1;
        while (rows < arr.length && cums >= 0) {
            if (arr[rows][cums] == key) {
                showLog(rows, cums);
                return true;
            } else if (arr[rows][cums] < key) {
                rows++;;
            } else if (arr[rows][cums] > key) {
                cums--;
            }
        }
        return false;
    }

    private static void showLog(int rows, int cums) {
        System.out.println("找到原素 arr[" + rows + "][" + cums+"]");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值