Share my 7m C++ Solution, in place.


  • 1
    D
    class Solution {
    public:
        void rotate(vector<vector<int> > &matrix) {
            int n = matrix.size();
            int lo = 0, hi = n-2;
            while(lo <= hi){
                doRotation(matrix, lo, hi, n);
                lo++;
                hi--;
            }
            return;
        }
    private:
        void doRotation(vector<vector<int> > &matrix, int p, int q, int n){
            int tmp;
            for(int j = p; j<=q; j++){
                    tmp = matrix[p][j];
                    matrix[p][j] = matrix[n-1-j][p];
                    matrix[n-1-j][p] = matrix[n-1-p][n-1-j];
                    matrix[n-1-p][n-1-j] = matrix[j][n-1-p];
                    matrix[j][n-1-p] = tmp;
            }
            return;
        }
    };
    

    I treat this matrix as a swirl, and start from the outskirt.
    For the most outer level, we only need to deal with the 0 to n-2 entries of each edge.
    Then we do the same thing from level 0 to level n/2-1. It's simple, linear time and in place :)


  • 0
    L
    This post is deleted!

Log in to reply
 

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