189. Rotate Array (Leetcode)

PHOTO EMBED

Tue Oct 05 2021 12:13:11 GMT+0000 (UTC)

Saved by @Sakshamkashyap7 #c++

class Solution {
public:
    void myReverse(vector<int> &nums,int start, int end)   {
        while(start < end)  {
            swap(nums[start++], nums[end--]);
        }
    }
    void rotate(vector<int>& nums, int k) {
        if(nums.size()<2)   return;
        k = k % nums.size();
        myReverse(nums, 0, nums.size() - k - 1);
        myReverse(nums, nums.size()-k, nums.size() - 1);
        myReverse(nums, 0 , nums.size() - 1);
    }
};
content_copyCOPY

Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]

https://leetcode.com/problems/rotate-array/