本题不算难理解,但是解法很炫,第一次碰到,难免做不出来,而且由于带有Binary Search的Tag,会让人不由自主的往Binary Search想。
    其实,可以把本题想做一个Tree,右上角为顶点

    • target < matrix[i][j]: 向下移动
    • target == matrix[i][j]: 找到了
    • target > matrix[i][j]: 向左移动

    image.png
    示意图如上所示

    • 时间复杂度:240. Search a 2D Matrix II - 图2
    • 空间复杂度:240. Search a 2D Matrix II - 图3

    代码如下:

    1. class Solution {
    2. public boolean searchMatrix(int[][] matrix, int target) {
    3. if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
    4. return false;
    5. }
    6. int row = 0;
    7. int col = matrix[0].length - 1;
    8. while (row < matrix.length && col >= 0) {
    9. int val = matrix[row][col];
    10. if (target == val) {
    11. return true;
    12. }
    13. else if (target > val) {
    14. ++row;
    15. }
    16. else {
    17. --col;
    18. }
    19. }
    20. return false;
    21. }
    22. }

    Tree