Share my very concise Java solution, using the same binary search code for both row and col


  • 0
    public boolean searchMatrix(int[][] matrix, int target) {
        int rowN = matrix.length, colN = matrix[0].length;
        int[] firstColumn = new int[rowN];
        for (int i = 0; i < rowN; i++)  firstColumn[i] = matrix[i][0];
        int row = search(firstColumn, 0, rowN-1, target);
        int col = search(matrix[row], 0, colN-1, target);
        return matrix[row][col] == target;
    }
    
    private int search(int[] A, int L, int R, int target) {
        while (L < R) {
            int M = L + (R - L >> 1) + 1;  
            if      (A[M] > target)    R = M - 1;
            else                       L = M;
        }
        return L;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.