Sharing my 24ms C++ solution


  • 2
    T
    class Solution {
    private:
        void rotateHelper(vector<int>& nums, int left, int right)
        {
            int i = left, j = right;
            while(i<j)
            {
                swap(nums[i], nums[j]);
                i++;
                j--;
            }
        }
        
    public:
        void rotate(vector<int>& nums, int k) {
            int n = nums.size();
            if(k==0 || n<=1)
                return;
            
            k= k%n;
            rotateHelper(nums, 0, n-1);
            rotateHelper(nums, 0, k-1);
            rotateHelper(nums, k, n-1);
        }
    };

Log in to reply
 

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