剑指offer
第一次使用java开始刷题,计划两个月刷完剑指offer,加油!小蒋
一、 题目
//在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个
//整数,判断数组中是否含有该整数。
//
//
//
// 示例:
//
// 现有矩阵 matrix 如下:
//
//
//[
// [1, 4, 7, 11, 15],
// [2, 5, 8, 12, 19],
// [3, 6, 9, 16, 22],
// [10, 13, 14, 17, 24],
// [18, 21, 23, 26, 30]
//]
//
//
// 给定 target = 5,返回 true。
//
// 给定 target = 20,返回 false。
//
//
//
// 限制:
//
// 0 <= n <= 1000
//
// 0 <= m <= 1000
二、 解答
Solution1
这道题的数组是有序排列的,所以让我自然而然的想到了二分查找,但一般的二分查找都是应用于一维数组,所以我针对二分查找,思考了一下,大概可以称呼为二维二分查找。 一维中每次舍弃左段或者右段,在二维中就是每次舍弃左上或右下四分之一的空间。 之后进行递归查找剩余空间(此处可以将三部分矩形合并成两部分)。class Solution {
public boolean find(int[][] matrix, int target, int xf, int xe, int yf, int ye){
if (xf == xe || yf == ye) {
return false;
}
int xm = (xf + xe) / 2, ym = (yf + ye) / 2;
if (matrix[xm][ym] == target) {
return true;
}
if (matrix[xm][ym] < target) {
if (find(matrix, target, xm + 1, xe, yf, ye)) {
return true;
}
if (find(matrix, target, xf, xm + 1, ym + 1, ye)) {
return true;
}
}
if (matrix[xm][ym] > target) {
if (find(matrix, target, xf, xm, yf, ye)) {
return true;
}
return find(matrix, target, xm, xe, yf, ym);
}
return false;
}
public boolean findNumberIn2DArray (int[][] matrix, int target){
if (matrix.length == 0) {
return false;
}
return find(matrix, target, 0, matrix.length, 0, matrix[0].length);
}
}
三、 优秀代码分享
在leetcode还看见了更简洁的代码,但是我觉得一看到有序,我脑子里第一想到的就是二分查找,所以此方法虽然空间复杂度更高,但对我来说更加适用,更简洁的代码也在下面进行分享class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
int i = matrix.length - 1, j = 0;
while(i >= 0 && j < matrix[0].length)
{
if(matrix[i][j] > target) i--;
else if(matrix[i][j] < target) j++;
else return true;
}
return false;
}
}
其实就是从左下角找起,先往上走,消去行,往右走,消去列,最多走的步数就是martix的行列之和了