LCR-121 二维数组查找

 

要在二维数组 plants 中查找目标高度值 target,可以利用该数组的特性来设计一个高效的查找算法。由于每行中的元素从左到右递增,每列中的元素从上到下递增,我们可以从矩阵的右上角开始查找。具体方法如下:

  1. 从矩阵的右上角元素开始。
  2. 如果当前元素等于 target,返回 true
  3. 如果当前元素大于 target,则移动到左侧一列。
  4. 如果当前元素小于 target,则移动到下方一行。
  5. 重复以上步骤,直到找到 target 或者矩阵遍历完毕。

这是因为在右上角,如果当前元素比目标值大,说明目标值一定不在当前元素所在列的右侧,可以排除当前列;如果当前元素比目标值小,说明目标值一定不在当前元素所在行的上方,可以排除当前行。

以下是实现代码:

public class Solution {
    public boolean searchMatrix(int[][] plants, int target) {
        if (plants == null || plants.length == 0 || plants[0].length == 0) {
            return false;
        }

        int rows = plants.length;
        int cols = plants[0].length;

        // 从右上角开始
        int row = 0;
        int col = cols - 1;

        while (row < rows && col >= 0) {
            if (plants[row][col] == target) {
                return true;
            } else if (plants[row][col] > target) {
                col--;
            } else {
                row++;
            }
        }

        return false;
    }
}

示例

  1. 输入:plants = [[2,3,6,8],[4,5,8,9],[5,9,10,12]], target = 8
    • 输出:true
    • 过程:从右上角开始(8),直接找到目标值。
  2. 输入:plants = [[1,3,5],[2,5,7]], target = 4
    • 输出:false
    • 过程:从右上角开始(5),比目标值大,左移到3,再比目标值小,下移到5,再比目标值大,左移到2,最后比目标值小,但已经到达矩阵左下角,没有找到目标值。

时间复杂度 O(m + n)。

本文遵守 Attribution-NonCommercial 4.0 International 许可协议。 Attribution-NonCommercial 4.0 International