题目链接https://leetcode.com/problems/rotate-array/
这道题主要是想明白rotate是怎样完成的,举个例子
{1,2,3,4,5,6,7}, k=3
我们发现完成rotate 3需要进行一下三步
1)reverse array {1,2,3,4,5,6,7} => {7,6,5,4,3,2,1}
2)reverse array positions [0,..,k - 1] {7,6,5,4,3,2,1} => {5,6,7,4,3,2,1}
3) reverse array positions [k,...,n - 1] {5,6,7,4,3,2,1} => {5,6,7,1,2,3,4}
另外,如果k大于n的话,只需将k取成k%n即可。
于是代码如下
class Solution { public: void rotate(int nums[], int n, int k) { k = k % n; for(int i = 0; i < n / 2; i++) { nums[i] ^= nums[n - 1 - i]; nums[n - 1 -i] ^= nums[i]; nums[i] ^= nums[n - 1 - i]; } for(int i = 0; i < k / 2; i++) { nums[i] ^= nums[k - 1 - i]; nums[k - 1 -i] ^= nums[i]; nums[i] ^= nums[k - 1 - i]; } for(int i = k; i < (n + k) / 2; i++) { nums[i] ^= nums[n - 1 - (i - k)]; nums[n - 1 - (i - k)] ^= nums[i]; nums[i] ^= nums[n - 1 - (i - k)]; } } };