m*n 的二维数组 plants 记录了园林景观的植物排布情况,具有以下特性:

每行中,每棵植物的右侧相邻植物不矮于该植物;

每列中,每棵植物的下侧相邻植物不矮于该植物。

请判断 plants 中是否存在目标高度值 target。

示例 1:

**输入:**plants = [[2,3,6,8],[4,5,8,9],[5,9,10,12]], target = 8

**输出:**true

示例 2:

**输入:**plants = [[1,3,5],[2,5,7]], target = 4

**输出:**false

提示:

0 <= n <= 1000

0 <= m <= 1000

考虑数组的有序性,[0][0]为最小值,[m][n]为最大值

想到另两个对角点,对于右上角,向左变小,向右变大,所以寻找target的过程就是向左向右选择的过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool findTargetIn2DPlants(vector<vector<int>> &plants, int target) {
if (plants.empty())
return false;
int y = plants[0].size() - 1;
int x = 0;

while (x >= 0 && x < plants.size() && y < plants[x].size() && y >= 0) {
int ans = plants[x][y];
if (ans > target)
y--;
else if (ans < target)
x++;
else
return true;
}
return false;
}
};