[leetcode] 189.Rotate Array

来源:互联网 发布:炫酷团队网站源码 编辑:程序博客网 时间:2024/04/29 12:00

题目:
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.
题意:
给一个数组,把元素往右循环移动k步。首先让k%=n。无需多余移动。
题目让使用三种方法。

  1. 第一种方法,把左边n-k个元素翻转,把后面k个元素翻转。然后把整体翻转。
    代码如下:
class Solution {public:    void rotate(vector<int>& nums, int k)     {        int size = nums.size();        if(size == 0)return;        k %= size;        reverse(nums, 0, size - k - 1);        reverse(nums, size - k, size - 1);        reverse(nums, 0, size - 1);    }    void reverse(vector<int>& nums, int start, int end)    {        if(start == end)return;        while(start < end)        {            swap(nums[start], nums[end]);            start++;            end--;        }    }};
  1. 插入前面。
class Solution {public:    void rotate(vector<int>& nums, int k)     {        int size = nums.size();        if(size == 0)return;        k %= size;        nums.insert(nums.begin(), nums.end() - k, nums.end());        nums.erase(nums.end() - k, nums.end());    }};

3.使用O(k)额外空间先保存后面k个元素。

class Solution {public:    void rotate(vector<int>& nums, int k)     {        int size = nums.size();        if(size == 0)return;        k %= size;        vector<int> temp(nums.end() - k, nums.end());        for(int i = size - k - 1; i >= 0; i--)            nums[i + k] = nums[i];        for(int i = 0; i < k; i++)            nums[i] = temp[i];    }};
0 0
原创粉丝点击