题目描述:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
思路:根据题目条件,数组中的行和列都按照递增的顺序排序,所以使得这道题可以使用对角线的方法完成,可以从右上角的元素考虑,如果目标查找元素小于右上角的元素,那么不可能在右上角元素所在的列,如果目标大于剩余列的右上角的元素,那么不可能在该右上角元素所在的行。依照这个规律,就可以完成目标元素的查找。
public class MartrixFoundSolution {
public boolean find(int [][] array,int target) {
boolean found = false;
int rows = array.length;
int columns = array[0].length;
int row = 0;
int column = columns - 1;
while(row < rows && column >=0){
if(array[row][column] == target){
found = true;
break;
}else if(array[row][column] > target){
column--;
}else{
row++;
}
}
return found;
}
}