[LeetCode] 189. Rotate Array
Question
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.
Hint:
Cocould you do it in-place with O (1) extra space?
Train of Thought 1
The same idea as the string rotation operation.
Three-way flip: n-k before the first flip, k after the second flip, and all after the third flip.
Code 1
/* ---------------------------------------- * Date: 2014-02-25 * Author: SJF0115 * Title: 189. Rotate Array * URL: https://oj.leetcode.com/problems/rotate-array/ * result: AC * Source: LeetCode * blog: Author */# include
# Include
Using namespace std; class Solution {public: void rotate (int nums [], int n, int k) {if (n <= 1) {return ;} // if k = k % n; if (k <= 0) {return;} // if // n-k Reverse (nums, 0, n-k-1); // k Reverse (nums, n-k, n-1) After flip; // flip all Reverse (nums, 0, n-1);} private: void Reverse (int nums [], int left, int right) {int tmp; for (int I = left, j = right; I <j; ++ I, -- j) {// swap (nums [I], nums [j]) ;}// for}; int main () {Solution solution; int A [] = {1, 2, 4, 5, 6, 7}; int n = 7; int k = 2; solution. rotate (A, n, k); for (int I = 0; I <n; ++ I) {cout <