从左下角开始
public class Solution {
public boolean Find(int target, int [][] array) {
int i = array.length-1;
int j = 0;
while(i >= 0 && j <= array[0].length-1){
if(array[i][j] == target){
return true;
}
else if(target < array[i][j]){
i--;
}else{
j++;
}
}
return false;
}
}
从右上角开始
public class Solution {
public boolean Find(int target, int [][] array) {
int i = 0;//初始化行的值
int j = array[0].length-1;//初始化列的值
while(i <= array.length-1 && j >= 0){
if(array[i][j] == target){
return true;
}
else if(target < array[i][j]){
j--;
}else{
i++;
}
}
return false;
}
}
我giao。。为何我代码跑不动,额。。是我把他默认成行列都相同了。。吐了吐了,每个一维数组长度相同不代表他是n*n的数组
//首先判断数组不为空,否则直接返回false
if(array!=null && array.length > 0 && array[0].length > 0){
int row = 0; //初始化行的值
int col = array[0].length - 1; //初始化列的值
//循环遍历判断,寻找target
while(row <= array.length-1 && col >= 0){
if(target == array[row][col]){
return true;
}else if(target < array[row][col]){
col--;
}else{
row++;
}
}
}
return false;