The reference link: http://www.code123.cc/docs/leetcode-notes/binary_search/search_a_2d_matrix_ii.html
题解 - 自右上而左下
- 复杂度要求——O(m+n) time and O(1) extra space,同时输入只满足自顶向下和自左向右的升序,行与行之间不再有递增关系,与上题有较大区别。时间复杂度为线性要求,因此可从元素排列特点出发,从一端走向另一端无论如何都需要m+n步,因此可分析对角线元素。
- 首先分析如果从左上角开始搜索,由于元素升序为自左向右和自上而下,因此如果target大于当前搜索元素时还有两个方向需要搜索,不太合适。
- 如果从右上角开始搜索,由于左边的元素一定不大于当前元素,而下面的元素一定不小于当前元素,因此每次比较时均可排除一列或者一行元素(大于当前元素则排除当前行,小于当前元素则排除当前列,由矩阵特点可知),可达到题目要求的复杂度。
-
public class Solution { /** * @param matrix: A list of lists of integers * @param: A number you want to search in the matrix * @return: An integer indicate the occurrence of target in the given matrix */ public int searchMatrix(int[][] matrix, int target) { // write your code here int count = 0; if (matrix == null || matrix.length == 0) { return count; } if (matrix[0] == null || matrix[0].length == 0) { return count; } int nRow = matrix.length; int nCol = matrix[0].length; if (matrix[0][0] > target || matrix[nRow - 1][nCol - 1] < target) { return count; } int i = 0; int j = nCol - 1; while (i < nRow && j >= 0) { if (matrix[i][j] > target) { j--; } else if (matrix[i][j] < target) { i++; } else { i++; j--; count++; } } return count; } }