LeetCode:Rotate Array

来源:互联网 发布:免费直播软件 编辑:程序博客网 时间:2024/05/21 22:56


问题描述:

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.

思路:

方法一:使用O(K)个空间,复杂度为O(n),将后半段保存在数组中,然后将前半段后移,切记:是倒着移动!

方法二:使用O(N)个空间,复杂度为O(n),将前后半段分别存储,代码略。

代码:

public:    void rotate(vector<int>& nums, int k) {    int n = nums.size();    if(k == 0)    {        return;    }    else if(k > 0)    {        k = k % n;        int array[k];        for(int i = n - k,j = 0; i < n; ++ i,++ j)            array[j] = nums[i];        for(int i = n - k -1,j = n - 1; i >= 0; --i,--j)            nums[j] = nums[i];        for(int i = 0,j = 0; i < k; ++i,++j)            nums[i] = array[j];    }    else    {        k = k % n ;  k = n + k;  int array[k];        for(int i = n - k,j = 0; i < n; ++ i,++ j)            array[j] = nums[i];        for(int i = n - k -1,j = n - 1; i >= 0; --i,--j)            nums[j] = nums[i];        for(int i = 0,j = 0; i < k; ++i,++j)            nums[i] = array[j];    }    }};</span>


1 0