Simple java solution with explanation


  • 0
    H
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length == 0 || matrix[0].length == 0) {return false;}
        int row = matrix.length, col = matrix[0].length;
        int lo = 0, hi = row * col - 1;
        while (lo <= hi) {
            int mid = (lo + hi)/2;
            int temp = matrix[mid/col][mid%col];
            if (temp > target) {
                hi = mid - 1;
            } else if (temp < target) {
                lo = mid + 1;
            } else {
                return true;
            }
        }
        return false;
    }
    

    the idea is just treating it as the one-dimension array. The point is to transfer the index of one-dimension array to the index of two-dimension array.


Log in to reply
 

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