Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] was rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.
Rotating an array
Solution One:
Using the exchange of data, for the above n=7,k=3 situation, can be divided into three steps to complete:
- Exchange 1234 is 4321
- Exchange 567 is 765
- Exchange 4321765 is 5671234
Divide the operation into three steps:
Time complexity is O (N), spatial complexity is O (1)
classSolution { Public://Solution 1: Using the swap voidRotate vector<int>& Nums,intK) {intLength=nums.size (); K=k%length; Swapvector (Nums,0, length-k-1); Swapvector (nums,length-k,length-1); Swapvector (Nums,0, length-1); }voidSwapvector ( vector<int>&nums,intFirstintLast) { for(inti=first,j=last;i<j;i++,j--) {swap (nums[i],nums[j]); } }};
Solution Two:
Use a new array directly to hold the data, and then copy the new array to the given array.
The time complexity is O (n), and the spatial complexity is O (n).
class Solution {public: //直接使用一块新的内存 void rotate(vector<int>int k) { vector<int> result; int length=nums.size(); k%=length; result.insert(result.end(),nums.begin()+length-k,nums.end()); result.insert(result.end(),nums.begin(),nums.begin()+length-k); nums=result; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode189:rotate Array