leetcode189.轮转数组(leetcode189. Rotation array)-其他

leetcode189.轮转数组(leetcode189. Rotation array)

``````class Solution {
public:
void reverse(vector<int>& nums, int start, int end) {
while (start < end) {
swap(nums[start], nums[end]);
start += 1;
end -= 1;
}
}
void rotate(vector<int>& nums, int k) {
k %= nums.size();
reverse(nums, 0, nums.size() - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.size() - 1);
}
};``````
————————

The method I use is to create a new array to save, and then use the assign function to copy it to the original function. Note that the function is of void type, so I can’t directly return a new function.

Better way:

First flip the whole array left and right, then reverse the left and right parts according to K, and swap with double pointers

``````class Solution {
public:
void reverse(vector<int>& nums, int start, int end) {
while (start < end) {
swap(nums[start], nums[end]);
start += 1;
end -= 1;
}
}
void rotate(vector<int>& nums, int k) {
k %= nums.size();
reverse(nums, 0, nums.size() - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.size() - 1);
}
};``````