leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0189.cpp (662B)


      1 // O(n) memory solution
      2 class Solution {
      3   public:
      4     void rotate(vector<int> &nums, int k) {
      5         k %= nums.size();
      6         vector<int> t(k);
      7         for (int i = 0; i < k; i++)
      8             t[i] = nums[nums.size() - k + i];
      9         for (int i = nums.size() - k - 1; i >= 0; i--)
     10             nums[i + k] = nums[i];
     11         for (int i = 0; i < k; i++)
     12             nums[i] = t[i];
     13     }
     14 };
     15 
     16 // O(1) memory solution
     17 class Solution {
     18   public:
     19     void rotate(vector<int> &nums, int k) {
     20         k %= nums.size();
     21         reverse(nums.begin(), nums.end());
     22         reverse(nums.begin(), nums.begin() + k);
     23         reverse(nums.begin() + k, nums.end());
     24     }
     25 };