My C++(5 line) 4ms solution with explaination


  • 0
    R

    The first row is the last column of the rotated matrix.
    The second row is the second column & so on....

    Code:

    // the array
       1 2 3                 7 4 1
       4 5 6    ------>      8 5 2
       7 8 9                 9 6 3 //
            class Solution {
        public:
            void rotate(vector<vector<int>>& matrix) {
                vector<vector<int>> duplicate = matrix;
                int col = matrix[0].size()-1,row = matrix.size()-1;
                for(int i=0;i<=row;++i)//row
                    for(int j=0; j<=col; ++j)//column
                        matrix[j][col-i] = duplicate[i][j];
            }
        };

  • 0
    1

    you need to do this in-place,you can't use another vector<vector<int>>


Log in to reply
 

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