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.
解题思路
要求时间复杂度 O(M + N),空间复杂度 O(1)。其中 M 为行数,N 为 列数。
右上角的元素是它所在行的最大值、所在列的最小值。target 比它小时,这一列下面的数都更大,可以排除这一列;target 比它大时,这一行左边的数都更小,可以排除这一行。每次排除一行或一列,剩下的查找区间仍是一个矩形,它的右上角就是下一个要比较的元素。例如查找 5:15、11、7 都大于 5,依次排除最后三列;4 小于 5,排除第一行;下移到 5,找到。
public boolean findTargetIn2DPlants(int[][] plants, int target) {
if (plants == null || plants.length == 0 || plants[0].length == 0)
return false;
int rows = plants.length, cols = plants[0].length;
int r = 0, c = cols - 1; // 从右上角开始
while (r <= rows - 1 && c >= 0) {
if (target == plants[r][c])
return true;
else if (target > plants[r][c])
r++;
else
c--;
}
return false;
}