Gyh's Braindump

CN-04.Search a 2d matrix ii

tags
BinarySearchTree
source
leetcode-cn

Edge Cases

Solution

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null) return false;
        int R = matrix.length;
        if (R == 0) return false;
        int C = matrix[0].length;

        int r = 0, c = C - 1;
        while (r < R && c >= 0) {
            if (matrix[r][c] == target) return true;
            else if (matrix[r][c] < target) r++;
            else c--;
        }

        return false;
    }
}

Complexity

  • time: O(M + N)
  • space: O(1)