Share a brief code using STL


  • 4
    T

    The algorithm is O(n) time, O(1) space

    It has 3 steps:

    1. reverse nums from 0 to n-1;
    2. reverse nums from 0 to k-1;
    3. reverse nums from k to n-1;

    code:

    class Solution {
    public:
        void rotate(int nums[], int n, int k) {
            k %= n;
            reverse(nums, nums + n);
            reverse(nums, nums + k);
            reverse(nums + k, nums + n);
        }
    };

  • 0
    A
    void rotate(int nums[], int n, int k) {
        std::vector<int> vec(nums, nums + n);
        std::rotate(vec.begin(), vec.begin()+(k % n), vec.end());
    std::copy(vec.begin(), vec.end(), nums);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.