JAVA FAST INPLACE SOLUTION


  • 0
    T
    public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length - 1;
        int offset = 1 - n % 2;
        for (int i = 0; i <= n / 2; i++) {
            for (int j = 0; j <= n / 2 - offset; j++) {
               rotateswap(i, j, matrix); 
            }
        }
       return;
    }
    
    public void rotateswap(int i, int j, int[][] matrix) {
        int n = matrix.length - 1;
        int x = i;
        int y = j;
        int count = 4;
        int temp0 = matrix[x][y];
        while (count > 0) {
            int temp1 = matrix[y][n - x];
            matrix[y][n - x] = temp0;
            int tempx = x;
            x = y;
            y = n - tempx;
            temp0 = temp1;
            count--;
        }
        return;
    }
    

    }


  • 0
    T

    There's a lot of inversion going on there, consider:

    int offset = n % 2;
    for (int i = 0; i < n / 2 + offset; i++) {
        for (int j = 0; j < n / 2; j++) {

Log in to reply
 

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