判断数字是否存在二维数组中

package com.mooc;

public class Basic {

public static void main(String[] args) {
// 在一个二维数组中,每一行都按照从左到右递增的顺序排序
// ,每一列都按照从上到下递增的顺序排序。
// 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
int target = 22;
int target1 = 66;
int[][] a = { { 1, 3, 4 }, { 55, 66, 77 }, { 541, 4445, 6677 } };
System.out.println(contains(a, target));
System.out.println(contains(a, target1));
}

public static boolean contains(int[][] array, int target) {
for (int i = 0, j = array[i].length - 1; j>=0&&i < array.length - 1;) {
if (target > array[i][j]) {
i++;
continue;
}
if (target < array[i][j]) {
j–;
continue;
}
if (target == array[i][j]) {
return true;
}
}
return false;

}

}

猜你喜欢

转载自blog.csdn.net/weixin_37565521/article/details/89241430