1. 二维数组中的查找

本文介绍了一种在二维矩阵中查找特定元素的高效算法。通过利用矩阵的有序特性,采用类似二分查找的方法,从右上角开始,根据目标值与当前元素的大小关系,决定是在同一行左移还是在同一列下移,直至找到目标值或确定不存在于矩阵中。这种方法避免了全矩阵遍历,大大提高了查找效率。

常规解法

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2019/12/17 14:36
 * @Created by Cheng
 */
public class Solution {    
    public boolean Find(int target, int [][] matrix) {
        if (matrix == null || matrix.length < 1 || matrix[0].length < 1) return false;
        int row = 0, col = matrix.length - 1;
        while (row < matrix.length && col >= 0) {
            int cur = matrix[row][col];
            if (target < cur) {
                col--;
            } else if (target > cur) {
                row++;
            } else {
                return true;
            }
        }
        return false;
    }
}

配合二分查找

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2019/12/17 14:36
 * @Created by Cheng
 */
public class Solution {
    public boolean Find(int target, int [][] matrix ) {
        boolean ret = false;
        if (matrix == null || matrix.length < 1 || matrix[0].length < 1) return ret;
        int row = 0;
        int col = matrix[0].length - 1;
        while (row < matrix.length && col >= 0) {
            col = Arrays.binarySearch(matrix[row], 0, col + 1, target);
            if (col >= 0) {
                ret = true;
                break;
            }
            col = -col - 1;
            if (col == 0) break;
            col--;
            row = bSearch(matrix, col, row, target);
            if (row >= 0) {
                ret = true;
                break;
            }
            row = -row - 1;
            if (row == matrix.length) break;
        }
        return ret;
    }

    private int bSearch(int[][] matrix, int col, int fromIndex, int target) {
        int low = fromIndex;
        int high = matrix.length - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = matrix[mid][col];

            if (midVal < target)
                low = mid + 1;
            else if (midVal > target)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

山与长生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值