class Solution {
// 排除法O(m+n)
public boolean findTargetIn2DPlantsPCF(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0){
return false;
}
int m = matrix.length, n = matrix[0].length;
int i = 0, j = n-1;
while (i < m && j >= 0){
if (matrix[i][j] == target){
return true;
} else if (matrix[i][j] > target){
j--;
} else{
i++;
}
}
return false;
}
// 二分写法 O(m*logn)
public boolean findTargetIn2DPlants(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0){
return false;
}
int m = matrix.length, n = matrix[0].length;
for (int i = 0; i < m; i++){
int left = 0, right = n;
while (left < right){
int mid = left + (right - left) / 2;
if (matrix[i][mid] == target){
return true;
} else if (matrix[i][mid] > target){
right = mid;
} else{
left = mid + 1;
}
}
}
return false;
}
}
“`c++
class Solution {
public:
bool findTargetIn2DPlants(vector>& plants, int target) {
if (plants.size() == 0) return false;
int m = plants.size(), n = plants[0].size();
int i = 0, j = n-1;
while (i < m && j >= 0) {
if (plants[i][j] > target) j–;
else if (plants[i][j] < target) i++;
else return true;
}
return false;
}
};
```
共以下 6 个回答
// 1.暴力法
// 遍历二维矩阵,复杂度 O(m*n)
// 2.排除法
// 初始(x, y)为右上角(0, m-1)
// 如果target > matrix[x][y], 则第0行元素都比target小,可以舍弃, 坐标更新为(x+1, y), 继续查找
// 如果target < matrix[x][y], 则第j列元素都比target大,可以舍弃,坐标更新为(x, y-1), 继续查找
// target matrix[x][y] 返回TRUE,x,y越界也没有找到返回false
// 最坏情况为数据在左下角,恰好遍历完一行和一列, 时间复杂度O(m+n), 空间复杂度O(1)
// 3.二分查找, 每一行做一次二分,复杂度O(m*logn)
时间复杂度:O(n+m)
额外空间复杂度:O(1)
class Solution {
public boolean findTargetIn2DPlants(int[][] plants, int target) {
int i = 0, j = 0;
while(i >= 0 && j >= 0 && i < plants.length && j < plants[0].length){
if(target plants[i][j])
return true;
else if(target > plants[i][j]){
if(j < plants[0].length-1 && plants[i][j+1] <= target)
j++;
else
i++;
}else{
j–;
}
}
return false;
}
}
//时间Onm
//空间O1
二分+暴力
时间:O(m+n)
空间:O(1)
“`c++>& plants, int target) {
class Solution {
public:
bool findTargetIn2DPlants(vector
if (plants.size() == 0) return false;
int m = plants.size(), n = plants[0].size();
int i = 0, j = n-1;
while (i < m && j >= 0) {
if (plants[i][j] > target) j–;
else if (plants[i][j] < target) i++; else return true; } return false; } }; ```