Sharing my C++ solution using two swaps


  • 0
    T
    class Solution {
    private:
        void swapVector(vector<int>& a, vector<int>& b)
        {
            int tmp;
            for(int i=0; i<a.size(); i++)
            {
                tmp = b[i];
                b[i] = a[i];
                a[i] = tmp;
            }
        }
        
        void reverseVector(vector<vector<int>>& matrix)
        {
            int left = 0;
            int right = matrix.size()-1;
            while(left<right)
            {
                swapVector(matrix[left], matrix[right]);
                left++;
                right--;
            }
        }
        
    public:
        void rotate(vector<vector<int>>& matrix) {
            // (i, j) --> (j, n-i-1)
            // (i, j)-->(n-i-1, j) -->(j, n-i-1)
            reverseVector(matrix);
            for(int i=0; i<matrix.size(); i++)
                for(int j=i+1; j<matrix.size(); j++)
                    swap(matrix[i][j], matrix[j][i]);
        }
    };

Log in to reply
 

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