24ms simple and easy to understand c++ code.


  • 0
    M

    First I take the module of k%n = k_new and this is the effective number of rotate since for n rotation the sequence goes back to itself. Next I move elements from (n - k + 1) th to nth to the front and elements from 1st to (n-k) th to the end.

    class Solution {
    public:
    void rotate(vector<int>& nums, int k) {
        
        int k_new = k;
        
        if (nums.size() <= 1) return;
        if (k_new%nums.size() == 0) return;
        if (k_new%nums.size() != 0) k_new = k_new%nums.size();
        
        vector<int> nums_shift;
        
        for (int i = nums.size() -k_new; i < nums.size(); i++){
            nums_shift.push_back(nums[i]);
        }
        for (int i = 0; i < nums.size() - k_new; i++){
            nums_shift.push_back(nums[i]);
        }
        nums.clear();
        nums = nums_shift;
    }};

Log in to reply
 

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