题目:
我们可以右上角或者左下角的数为基准,进行对比,然后依次移动,查找我们想要的数:
java代码实现如下:
package 剑指offer;
public class FindInTwoArray {
public static void main(String[] args) {
// 首先来一个测试用的数组
int[][] shuzu = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
boolean result = find(shuzu,7);
System.out.println(result);
}
public static boolean find(int shuzu[][], int num) {
int len = shuzu.length;
int i = 0;
int j = len - 1;
int count = 0;
while (i < len && j >= 0) {
++count;
if (shuzu[i][j] > num) {
j--;
} else if (shuzu[i][j] < num) {
i++;
} else {
System.out.println("查找次数为:"+count);
return true;
}
}
return false;
}
}
控制台打印如下:
我这里打印出了是否查找到,如果找到了,同时还打印了查找次数