3ms C++ in-place code


  • 0
    M

    Simple and fast, in-place.

    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            transp(matrix);
            flip(matrix);
        }
        
    private:
        
        void transp(vector<vector<int> >& matrix) {
            const int n = matrix.size();
            for (int i = 0; i < n; i ++) {
                for (int j = 0; j < i; j ++) {
                    matrix[i][j] = matrix[i][j] + matrix[j][i];
                    matrix[j][i] = matrix[i][j] - matrix[j][i];
                    matrix[i][j] -= matrix[j][i];
                }
            }
        }
        
        void flip(vector<vector<int> >& matrix) {
            const int n = matrix.size();
            for (int i = 0; i < n; i ++) {
                for (int j = 0; j < n / 2; j ++) {
                    matrix[i][j] = matrix[i][j] + matrix[i][n - j - 1];
                    matrix[i][n - j - 1] = matrix[i][j] - matrix[i][n - j - 1];
                    matrix[i][j] -= matrix[i][n - j - 1];
                }
            }
        }
    };
    

Log in to reply
 

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