[LeetCode] 189. Rotate Array

来源:互联网 发布:淘宝怎么用手机号登陆 编辑:程序博客网 时间:2024/06/10 12:12

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II

class Solution {public:    void rotate(vector<int>& nums, int k) {        const int n = nums.size();        if ((k = k % n) == 0) return;        vector<int> copied(nums);        for (int i = 0; i < n; i++)            nums[i] = copied[(n - k + i) % n];    }};

这里写图片描述这里写图片描述

// 空间复杂度O(1)class Solution {public:    void rotate(vector<int>& nums, int k) {        int n = nums.size();        vector<int>::iterator it = nums.begin();        for (; k %= n; n -= k, it += k) {            for (int i = 0; i < k; i++)                swap(it[i], it[n - k + i]);        }    }};

这里写图片描述这里写图片描述