Two solutions in C++


  • 0

    Simple 3 lines but O(n) space

    void rotate(vector<int>& nums, int k) {
            for(int i=0;i<k;i++){
                nums.insert(nums.begin(),*(nums.end()-1));
                nums.erase(nums.end()-1);
            }
        }
    

    O(1) space

    void rotate(vector<int>& nums, int k) {
            int n=nums.size();
            int start=0;
            while(k%=n){
            for(int i=0;i<k;i++) swap(nums[start+i],nums[start+n-k+i]);
            n-=k;
            start+=k;
            }
        }
    

Log in to reply
 

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