题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例
编程思路
采用《剑指Offer》书中的思路:首先选取数组右上角(或者是左下角,同理)的数字,如果该数字等于要查找的数字,则查找过程结束;如果该数字大于要查找的数字,则剔除这个数字所在的列,向左搜寻(缩小范围);如果该数字小于要查找的数字,则剔除这个数字所在的行,向下搜寻。
方法一:暴力实现
public class q_1 {
public boolean Find(int target, int [][] array) {
for(int i=0;i<array.length;i++){
for(int j=0;j<array.length;j++){
if(array[i][j]==target){
System.out.println("数组中存在该整数"+","+"下标为"+i+" "+j);
return true;
}
// System.out.println(i+" "+j+" "+array[i][j]);
}
}
System.out.println("数组中不存在该整数");
return false;
}
public static void main(String[] args){
int target=11;
int[][] a={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
q_1 solution=new q_1();
solution.Find(target,a);
}
}
方法二
public class q_1 {
public boolean Find(int target, int [][] array) {
int rows = array.length; //二维数组的行长度
int cols = array[0].length; //二维数组的列长度
if(array != null && rows > 0 && cols > 0) {
int row = 0;
int col = cols - 1;
while(row < rows && col >= 0) {
int temp = array[row][col];
if (temp > target) {
col--; //待查找的数小于“角值”时,则行不变列-1向左搜寻
}
else if (temp < target) {
row++; //待查找的数大于“角值”时,则列不变行+1向下搜寻
}
else {
return true;
}
}
}
return false;
}
public static void main(String[] args){
int target=9;
int[][] a={{1,2,3},{4,5,6},{7,8,9}};
q_1 solution=new q_1();
boolean flag=solution.Find(target,a);
if(flag) {
System.out.println("已找到");
}
}
}
public class q_1 {
public boolean Find(int target, int [][] array) {
int rows = array.length; //二维数组的行长度
int cols = array[0].length; //二维数组的列长度
if(array != null && rows > 0 && cols > 0) {
int row = 0;
int col = cols - 1;
while(row < rows && col >= 0) {
int temp = array[row][col];
if (temp > target) {
col--; //待查找的数小于“角值”时,则行不变列-1向左搜寻
}
else if (temp < target) {
row++; //待查找的数大于“角值”时,则列不变行+1向下搜寻
}
else {
return true;
}
}
}
return false;
}
public static void main(String[] args){
int target=9;
int[][] a={{1,2,3},{4,5,6},{7,8,9}};
q_1 solution=new q_1();
boolean flag=solution.Find(target,a);
if(flag) {
System.out.println("已找到");
}
}
}