Java in-place


  • 3

    I store the sums and counts in the higher bits and divide them in a second pass.

    public int[][] imageSmoother(int[][] M) {
        int m = M.length, n = M[0].length;
        for (int i=0; i<m; i++)
            for (int j=0; j<n; j++)
                for (int I=i-1; I<i+2; I++)
                    for (int J=j-1; J<j+2; J++)
                        if (I >= 0 && I < m && J >= 0 && J < n)
                            M[i][j] += 256 + M[I][J] % 256 * 4096;
        for (int i=0; i<m; i++)
            for (int j=0; j<n; j++)
                M[i][j] = M[i][j] / 4096 / (M[i][j] / 256 % 16);
        return M;
    }
    

    After my first pass, each M[i][j] holds:

    • In bits 0-7: The original value.
    • In bits 8-11: The number of contributing cells (i.e., the number of neighbors, plus 1 (for the cell itself)). That's why I add 256 for each contributing cell.
    • In bits 12-31: The sum of the original values of the contributing cells. That's why I add the original value of M[I][J] times 4096.

  • 0

    @StefanPochmann said in Java in-place:
    you are as neat as always,but could you please explain the line below a little bit?

    M[i][j] += 256 + M[I][J] % 256 * 4096;


  • 1

    @wxl163530 I added more explanation. Is it clear now?


  • 0

    @StefanPochmann clear enough! Thx~


  • 0
    W

    Awesome solution~! Thanks.


Log in to reply
 

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