暴力的话时间复杂度到了O(N*M)
从数据状况出发考虑还有一种解法
例:
1 3 4 5
2 4 6 7
5 8 9 11
8 12 13 16
假如说是找6
我们从左下角开始走
一开始是8 比6大 那么就不用考虑8的右面了 直接往上走
走到了5 5比6小 那么5上面的都会比6小 向右走
走到了8 8比6大 那么8的右面和下面都比6大 向上走
走到了4 4比6大 那么4的上面都会比6小 向右走
找到了6 true
。。。。
一直到了越界还没有找到 那么返回false
这样的话时间复杂度到了O(M+N)
public static boolean findNum(int[][] arr, int num) {
int a = 0;
int b = arr[0].length - 1;
while (a < arr.length && b > -1) {
if (arr[a][b] == num) {
return true;
} else if (arr[a][b] > num) {
b--;
} else {
a++;
}
}
return false;
}
从右上角等等那几个角落出发也是同理
public static boolean findNumNew(int[][] arr, int num) {
int a = arr.length - 1;
int b = 0;
while(a > -1 && b < arr[a].length) {
if (arr[a][b] == num) {
return true;
} else if (arr[a][b] < num) {
b++;
} else {
a--;
}
}
return false;
}
测试
public static void main(String[] args) {
int[][] arr = new int[][]{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}};
int num1 = 11;
int num2 = 0;
System.out.println(findNum(arr, num1));
System.out.println(findNum(arr, num2));
System.out.println("=================");
System.out.println(findNumNew(arr, num1));
System.out.println(findNumNew(arr, num2));
}