Rotate an Array

Rotate an Array 90 degrees clockwise without extra space.

e.g: [[1,2,3],[4,5,6],[7,8,9]] -> [[7,4,1],[8,5,2],[9,6,3]]

Solution: we can take an example of 5*5 matrix and take two points to see the transformation("->"means reaches)

(0,1)->(1,4)->(4,3)->(3,0)->(0,1)

(1,2)->(2,3)->(3,2)->(2,1)->(1,2)

That is (i, j)->(j, n-i)->(n-i, n-j)->(n-j, i)->(i, j) , n = len-1

We rotate the whole array layer by layer and there will be len/2 layers to be rotated

for layer l (from 0) the start index is l and the end index is l and the end index is n-l

we do not need to consider the last one(n-l) as it will be considered when the first one is visited.

Code:

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length-1, l = matrix.length/2;
        //every layer
        for(int i = 0; i < l; i++){
            for(int j = i; j < n-i; j++){
                //(i,j)->(j, n-i)->(n-i, n-j)->(n-j, i)->(i, j) n is len-1
                int temp_val = matrix[i][j];
                matrix[i][j] = matrix[n-j][i];
                matrix[n-j][i] = matrix[n-i][n-j];
                matrix[n-i][n-j] = matrix[j][n-i];
                matrix[j][n-i] = temp_val;
            }
        }
    }
}
View Code

 

posted @ 2017-06-16 12:36  小风约定  阅读(54)  评论(0)    收藏  举报