Skip to main content

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: O(N)O(N)

  • S: O(1)O(1)

  • 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: O(N)O(N)
  • S: O(1)O(1)