for Robot Artificial Inteligence

4. Rotate Array

|

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k==0)
        {
            return;
        }
        int n = nums.size();
        int* A = new int[k+1];
        int* B = new int[n-k];
        for(int i=0; i<k+1;i++)
        {
            A[i]=nums[i]; // A = {1,2,3,4}
        }
        for(int i=1; i<n-k;i++)
        {
            B[i-1]=nums[i+k]; // B = {5,6,7}
        }
        for(int i =0; i<n-k-1;i++) // 7-3-1 = 3
        {
            nums[i] = B[i];
            // std::cout<<nums[i]<<" ,";
        }
        for(int i = 0; i<k+1;i++) // 0,1,2,3<3
        {
            nums[k+i] = A[i];
        }


    }
};
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k==0)
        {
            return;
        }
        int n = nums.size();
        vector<int> copynums(n);
        for(int i = 0; i<n; i++)
        {
            copynums[i] = nums[i];
        }

        //rotate
        for(int i = 0; i<n; i++)
        {
            nums[(i+k)%n] = copynums[i];
        }
    }
};

Comments