Topic:
Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array is [1,2,3,4,5,6,7] 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.
Answer:
Loop right shift of the array:
Three flips, time complexity O (n) without opening up additional space
1 classSolution {2 Public:3 voidRotate (vector<int>& Nums,intk) {4 intI,temp,n;5n=nums.size ();6 if(n==0){7 return;8 }9 Else{Tenk=k%N; One for(i=0;i< (N-K)/2; i++){ Atemp=Nums[i]; -nums[i]=nums[n-k-1-i]; -nums[n-k-1-i]=temp; the } - for(i=n-k;i< (n2-K)/2; i++){ -temp=Nums[i]; -nums[i]=nums[n*2-k-1-i]; +nums[n*2-k-1-i]=temp; - } + for(i=0; i<n/2; i++){ Atemp=Nums[i]; atnums[i]=nums[n-1-i]; -nums[n-1-i]=temp; - } - } - } -};
Note the use of sizeof () and size ():
Size () is a function of the size (length) defined in a class, such as String A; A.size () asks for the size of a.
sizeof () is a standard identifier defined in the C language that is used to calculate the spatial size of a variable, such as String a;sizeof (a), which is the size of the memory space occupied by a.
189. Rotate Array