LeetCode Rotate Array
Rotate Array Total Accepted: 12759 Total Submissions: 73112 My Submissions Question Solution
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [, 7] is rotated to [, 4].
Note:
Try to come up as your solutions as you can, there are at least 3 different ways to solve this problem.
Loop array. n indicates the length of the array, and k indicates the number of times the array is moved to the right.
Solution 1:
Class Solution {public: void rotate (int nums [], int n, int k) {if (n = 0) return; k = k % n; // when k is greater than n, n cycles return to the initial position. Therefore, if (k = 0) return can be omitted several times; int * s = new int [k]; // to expand and move in one step, apply for k extra space to save the removed element for (int I = 0; I
= 0; -- j) nums [j + k] = nums [j]; // move for (int I = 0; I
Extra space required O (k % n)
33/33 test cases passed.
Status: Accepted
Runtime: 29 MS
Solution 2 (obtain the network ):
Three-way flip: n-k before the first flip, k after the second flip, and all after the third flip.
class Solution {public: void rotate(int nums[], int n, int k) { if(n==0)return ; k=k%n; if(k==0)return ; reverse(nums,n-k,n-1); reverse(nums,0,n-k-1); reverse(nums,0,n-1); } void reverse(int nums[],int i,int j) { for(;i
33 / 33 test cases passed.
Status: Accepted
Runtime: 26 ms