2014-05-11 03:56
原题:
Given an integer array. Perform circular right shift by n.
Give the best solution.
题目:给数组进行循环移位,给出最优解。
解法:首先要考虑n的范围,对于负数和超过数组长度的数,先进行取模操作。然后用三次反转数组就可以完成循环移位。
代码:
1 // http://www.careercup.com/question?id=6282862240202752 2 #include <algorithm> 3 #include <iostream> 4 #include <vector> 5 using namespace std; 6 7 void reverse(vector<int> &v, int ll, int rr) 8 { 9 int n = (int)v.size(); 10 11 if (ll > rr) { 12 swap(ll, rr); 13 } 14 if (ll < 0 || ll > n - 1 || rr < 0 || rr > n - 1) { 15 return; 16 } 17 while (ll < rr) { 18 swap(v[ll], v[rr]); 19 ++ll; 20 --rr; 21 } 22 } 23 24 void rightShift(vector<int> &v, int k) 25 { 26 int n = (int)v.size(); 27 28 if (n == 0) { 29 return; 30 } 31 k = k >= 0 ? k % n : (n - (n - k) % n) % n; 32 if (k == 0) { 33 return; 34 } 35 reverse(v, 0, n - k - 1); 36 reverse(v, n - k, n - 1); 37 reverse(v, 0, n - 1); 38 } 39 40 int main() 41 { 42 vector<int> v; 43 int n, k; 44 int i; 45 46 while (cin >> n && n > 0) { 47 v.resize(n); 48 for (i = 0; i < n; ++i) { 49 cin >> v[i]; 50 } 51 cin >> k; 52 rightShift(v, k); 53 for (i = 0; i < n; ++i) { 54 i ? (cout << ' '), 1 : 1; 55 cout << v[i]; 56 } 57 cout << endl; 58 59 v.clear(); 60 } 61 62 return 0; 63 }