classSolution { public: voidrotate(vector<int> &nums, int k){ int n; int tmp; int pos;
n = nums.size(); vector<int> vec(n);
for (int i = 0; i < n; i++) { pos = (i + k) % n; vec[pos] = nums[i]; } nums = std::move(vec); } };
Another clever method: After moving the elements of the array to the right by k times, the tailk mod nelements will move to the head of the array, and the remaining elements will move backward by k mod n positions.
This method is array reversal: we can first reverse all elements, so that the tailk mod nelements are moved to the head of the array, then we reverse the elements in the interval [0, k mod n - 1] and the interval [k mod n, n - 1] to get the final answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<algorithm> classSolution { public: voidrotate(vector<int>& nums, int k){ int n = nums.size();
k %= n;
std::reverse(nums.begin(), nums.begin() + n - k); std::reverse(nums.begin() + n - k, nums.end()); std::reverse(nums.begin(), nums.end());
} };
leetcode hot 100 rewrite
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<vector> #include<algorithm>
using std::vector;
classSolution { public: voidrotate(vector<int> &nums, int k) { int n = nums.size();
k = k % n;
std::reverse(nums.begin(), nums.begin() + n - k); std::reverse(nums.begin() + n - k, nums.end()); std::reverse(nums.begin(), nums.end()); } };