My Simple Fast Java Solution


  • -2
    Y
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
        
        // searching starts from top right corner
        int i = 0;
        int j = matrix[0].length - 1;
        
        while(j >= 0 && (i <= matrix.length - 1))
        {
            if (matrix[i][j] < target)
            {
                i++;
            } else if (matrix[i][j] > target)
            {
                j--;
            } else {
                // matrix[i][j] == target
                return true;
            }
        }
        
        return false;
    }

Log in to reply
 

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