现有矩阵 matrix 以下:java
[ [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
。python
给定 target = 20
,返回 false
。算法
这道题本质上就是遍历二维数组,咱们能够直接遍历,可是因为数组中的数据是存在规律的(下大于上、右大于左),因此咱们能够根据其规律,对其进行相似于“剪枝”的操做。编程
这里咱们是从左下角开始遍历的,即示例中的18。这样遍历的好处是,比18大的元素,都在其右侧,比18小的元素,都在其上方。数组
若是从1开始遍历,不管是下方元素,仍是右侧元素,都是大于1的。须要额外进行比较(比较下方和右侧元素和target的大小)。app
class Solution { public boolean searchMatrix(int[][] matrix, int target) { // check if (matrix == null || matrix.length == 0) { return false; } if (matrix[0] == null || matrix[0].length == 0) { return false; } // 肯定边界 int bottom = matrix.length - 1; int right = matrix[0].length - 1; // 肯定起点 int i = bottom, j = 0; while (i >= 0 && j <= right) { if (matrix[i][j] > target) { i--; } else if (matrix[i][j] < target) { j++; } else { return true; } } return false; } }
class Solution: def searchMatrix(self, matrix, target): # check if not matrix and len(matrix) == 0: return False if not matrix[0] and len(matrix[0]) == 0: return False # 肯定边界 bottom, right = len(matrix) - 1, len(matrix[0]) - 1 i, j = bottom, 0 while i >= 0 and j <= right: if matrix[i][j] > target: i -= 1 elif matrix[i][j] < target: j += 1 else: return True return False