189. Rotate Array
- Use Build-in Reverse() Function
class Solution {
public:
void rotate(vector<int>& nums, int k)
{
reverse(nums.begin(), nums.end());
k %= nums.size();
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
};
-
T:
-
S:
-
Two Pointers
class Solution {
public:
void rotate(vector<int>& nums, int k)
{
int left = 0, right = nums.size() - 1;
reverseArray(nums, left, right);
k %= nums.size();
left = 0, right = k - 1;
reverseArray(nums, left, right);
left = k, right = nums.size() - 1;
reverseArray(nums, left, right);
}
void reverseArray(vector<int>& nums, int left, int right)
{
while (left < right)
{
swap(nums[left], nums[right]);
++left; --right;
}
}
};
- T:
- S: