本文共 1372 字,大约阅读时间需要 4 分钟。
在一个n×m的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
[ [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]]
限制:
这种方法充分利用了矩阵的有序性质,能够在较少的查找次数内找到目标值,时间复杂度为O(log n + log m)。
public class Solution { public boolean findNumberIn2DArray(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false; } int rows = matrix.length; int cols = matrix[0].length; int row = 0; int col = cols - 1; while (row < rows && col >= 0) { int num = matrix[row][col]; if (num == target) { return true; } else if (target > num) { row++; } else { col--; } } return false; }}
这种方法高效且简洁,能够在较短时间内完成查找任务,适用于大规模的二维数组。
转载地址:http://yydmz.baihongyu.com/