How do you rotate a two dimensional array?

后端 未结 30 3060
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  隐瞒了意图╮
    2020-11-22 03:44

    Time - O(N), Space - O(1)

    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n / 2; i++) {
            int last = n - 1 - i;
            for (int j = i; j < last; j++) {
                int top = matrix[i][j];
                matrix[i][j] = matrix[last - j][i];
                matrix[last - j][i] = matrix[last][last - j];
                matrix[last][last - j] = matrix[j][last];
                matrix[j][last] = top;
            }
        }
    }
    

提交回复
热议问题