题目描述(剑指Offer4)
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例1
输入:
7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
返回值
true
代码:
public class Jzof04 {
public boolean Find(int target, int [][] array) {
int row = array.length;//行
int col = array[0].length;//列数
int r = 0,c = col - 1;
while ( r <= row-1 && c >= 0){
if (array[r][c] == target){
return true;
}else if (array[r][c] > target){
c--;
}else {
r++;
}
}
return false;
}
/*************自己的笨办法*****************/
public static boolean Find1(int target, int [][] array) {
int row = array.length;//行
int col = array[0].length;//列数
for (int i = col-1; i >=0 ; i--) {
if (array[0][i] <= target){
for (int j = 0; j < row; j++) {
if (array[j][i] == target){
return true;
}
}
}
}
return false;
}
public static void main(String[] args) {
int[][] a = {{1,2,8,9},
{2,4,9,12},
{4,7,10,13},
{6,8,11,15}};
System.out.println(Find1(1,a));
}
}