有规律的数组查找最快的方法我想到了二分法。
矩阵是从左到右,从上到下变大,那么对角线的找发会省时一些。
方法一:左上到右下
往右和往下都是增大,不能实现。
方法二:右下到左上
往上和往左都是减少,不能实现。
方法三:右上到左下
往左减少 往下增加,可实现。
方法四:左下到右上
往上减少 往右增加,可实现。
LeetCode题解里有个代码动画解释的很好:
https://leetcode-cn.com/problems/search-a-2d-matrix-ii/solution/sou-suo-er-wei-ju-zhen-ii-by-leetcode-2/
我的代码:(实现方法三)
public static boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length <= 0 || matrix[0].length <= 0) { //empty array
System.out.println("false");
return false;
} else {
int rows = matrix.length;
int cols = matrix[0].length;
// System.out.println("rows:" + rows + " cols:" + cols);
int r = 0;
int c = cols - 1; //from right top
// System.out.println("r:"+r+" c:"+c);
while (r < rows && r >= 0 && c < cols && c >= 0) {
if (matrix[r][c] == target) {
// System.out.println("true");
return true;
} else if (matrix[r][c] < target) {
r++;
} else {
c--;
}
}
// System.out.println("false");
return false;
}
}
题目来自LeetCode