classSolution{public:voidrotate(vector<int>&nums,intk){intn=nums.size();// Edge case handle: If the `k` is bigger than `n`.// E.g: `nums` has 7 elements and `k` is 10, the 10th rotation for this is same as 3rd rotation// Therefore, we can use modulo: 7 % 10 = 3if(n>0){// Avoiding dividing by 0k=k%n;}// We do our process for `k` stepsfor(inti=0;i<k;i++){// Step 1: Take the last elementintlastElement=nums.back();// Step 2: Remove the last elementnums.pop_back();// Step 3: Insert the last element to the firstnums.insert(nums.begin(),lastElement);}}};
classSolution{public:voidrotate(vector<int>&nums,intk){intn=nums.size();// Egde case: If the contains elements 1 or 0// There is nothing to rotateif(n<=1){return;}// Edge case: If `k` is larger than `n`k=k%n;// we avoid unnecessary work// Step 1: reverse the whole arrayreverse(nums.begin(),nums.end());// Step 2: revere the first `k` elementsreverse(nums.begin(),nums.begin()+k);// Step 3: reverse the rest part nowreverse(nums.begin()+k,nums.end());}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?