Skip to content

Latest commit

 

History

History
52 lines (44 loc) · 1.07 KB

File metadata and controls

52 lines (44 loc) · 1.07 KB
Screenshot 2024-03-27 at 11 55 18 PM

C++

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        k %= nums.size();

        function<void(int,int)> reverse = [&](int i, int j) {
            while(i < j) {
                swap(nums[i], nums[j]);
                i++;
                j--;
            }
        };

        reverse(0, nums.size() - 1);
        reverse(0, k - 1);
        reverse(k, nums.size() - 1);
    }
};

JS

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    function swap(i, j) {
        while(i < j) {
            [nums[i], nums[j]] = [nums[j], nums[i]];
            i++;
            j--;
        }
    }

    k %= nums.length;
    // 7 6 5 4 3 2 1
    swap(0, nums.length - 1);
    // 5 6 7 4 3 2 1
    swap(0, k - 1);
    // 5 6 7 1 2 3 4
    swap(k, nums.length - 1);
};