//! n,1 -> 三次反转耗时2*n;占地常数 classSolution { public: voidrotate(vector<int> &nums, int k){ int n = nums.size(); k = k % n; if (k == 0) return;
int changePoint = n - k - 1; // err1: // k不为0时changePoint也可能是0,所以之前判断changePoint为0返回时过不了[1,2] // 1这个测试 reverse(nums, 0, changePoint); reverse(nums, changePoint + 1, n - 1); reverse(nums, 0, n - 1); } voidreverse(vector<int> &nums, int left, int right){ while (left < right) { swap(nums[left], nums[right]); ++left; --right; } } };
TODO 环状替换
暂时不想去思考成什么样的环,i循环多少次,累了,先放个半成品
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: voidrotate(vector<int> &nums, int k){ int n = nums.size(); k = k % n; for (int i = 0; i < k; ++i) { int j = i; int temp = nums[i]; do { int next = (j + k) % n; swap(temp, nums[next]);