classSolution { public: voidrotate(vector<int>& nums, int k){ int n = nums.size(); if (n == 0 || k == 0) return; if (n <= k) { k = k % n; } reverse(nums.begin(), nums.end()); reverse(nums.begin(), nums.begin()+k); reverse(nums.begin()+k, nums.end()); } };
使用额外的临时数组
但是空间复杂度为O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: voidrotate(vector<int>& nums, int k){ int n = nums.size(); if (n == 0 || k == 0) return; if (n <= k) { k = k % n; } vector<int> ans(n, 0); for (int i = 0; i < n; i++) { ans[(i+k) % n] = nums[i]; } nums = ans; } };
classSolution { public: voidrotate(vector<int>& nums, int k){ int n = nums.size(); if (n == 0 || k == 0) return; if (n <= k) { k = k % n; } int count = 0, start = 0; while (count < n) { int current = start; do{ int next = (current + k) % n; swap(nums[current], nums[start]); current = next; count++; }while(current != start); start++; } } };
classSolution { public: voidrotate(vector<int>& nums, int k){ int n = nums.size(); if (n == 0 || k == 0) return; if (n <= k) { k = k % n; } //count为轮次,gcd表示两个数的最大公约数 int count = gcd(n,k); for (int start = 0; start < count; start++) { int current = start; do{ int next = (current + k) % n; swap(nums[current], nums[start]); current = next; }while(current != start); }