http://www.geeksforgeeks.org/array-rotation/
O(n), O(1)
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <queue> 5 #include <stack> 6 #include <string> 7 #include <fstream> 8 #include <map> 9 using namespace std; 10 11 int gcd(int a, int b) { 12 return b == 0? a : gcd(b, a % b); 13 } 14 15 void leftrotate(int arr[], int d, int n) { 16 for (int i = 0; i < gcd(d, n); i++) { 17 int tmp = arr[i]; 18 int j = i; 19 while (1) { 20 int k = j + d; 21 if (k >= n) k -= n; 22 if (k == i) break; 23 arr[j] = arr[k]; 24 j = k; 25 } 26 arr[j] = tmp; 27 } 28 } 29 30 int main() { 31 int arr[7] = {1, 2, 3, 4, 5, 6, 7}; 32 leftrotate(arr, 2, 7); 33 for (int i = 0; i < 7; i++) cout << arr[i] << " "; 34 return 0; 35 }
O(n), O(1)
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <queue> 5 #include <stack> 6 #include <string> 7 #include <fstream> 8 #include <map> 9 using namespace std; 10 11 void reverse(int arr[], int a, int b) { 12 for (int i = 0; i < (b-a)/2; i++) swap(arr[a+i], arr[b-1-i]); 13 } 14 15 void leftrotate(int arr[], int d, int n) { 16 reverse(arr, 0, d); 17 reverse(arr, d, n); 18 reverse(arr, 0, n); 19 } 20 21 int main() { 22 int arr[7] = {1, 2, 3, 4, 5, 6, 7}; 23 leftrotate(arr, 2, 7); 24 for (int i = 0; i < 7; i++) cout << arr[i] << " "; 25 return 0; 26 }