力扣
看《剑指offer》中的解释更加容易理解!!!
class Solution {
public boolean findTargetIn2DPlants(int[][] plants, int target) {
if (plants.length == 0 || plants[0].length == 0) {
return false;
}
int i = 0, j = plants[0].length - 1;
while (i >= 0
&& j >=0
&& i < plants.length
&& j < plants[0].length) {
if (plants[i][j] == target) {
return true;
} else if (plants[i][j] > target) {
--j;
} else {
++i;
}
}
return false;
}
}
1.笨蛋方法
复杂度为 O ( n 2 ) O(n^2) O(n2)
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
for(int i=0;i<array.size();i++){
for(int j=0;j<array[0].size();j++){
if(array[i][j]==target)
return true;
}
}
return false;
}
};
2.稍微聪明点的解法
算法是《剑指offer》上的思路,自己用c++实现,并在牛客网上AC。
Solution1:初始化为右上角的点
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int row = array.size(),col=array[0].size();//有row行,col列
if(row == 0 || col == 0) return false;
int i = 0,j = col-1;//初始化为第1行,最后一列
while(i <= row-1 && j >= 0){
if(array[i][j] == target)
return true;
else if(array[i][j] < target)
i++;
else if(array[i][j] > target)
j--;
}
return false;
}
};
Solution2:初始化为左下角的点
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int row = array.size(),col=array[0].size();//有row行,col列
if(row == 0 || col == 0) return false;
int i = row-1,j = 0;//初始化为最后1行,第1列
while(i >=0 && j <= col-1){
if(array[i][j] == target)
return true;
else if(array[i][j] > target)
i--;
else if(array[i][j] < target)
j++;
}
return false;
}
};
20190831重做
C++版
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if (!array.size() || !array[0].size())
return false;
int i = 0, j = array[0].size() - 1;
while (i <= array.size() - 1 && j >= 0) {
if (array[i][j] == target) {
return true;
} else if (array[i][j] < target){
i++;
} else {
j--;
}
}
return false;
}
};
Java版
public class Solution {
public boolean Find(int target, int [][] array) {
if (array.length == 0 || array[0].length == 0) {
return false;
}
int i = 0, j = array[0].length - 1;
while (i <= array.length - 1 && j >= 0) {
if (array[i][j] == target) {
return true;
} else if (array[i][j] < target){
i++;
} else {
j--;
}
}
return false;
}
}