189. Rotate Array

来源:互联网 发布:如何卸载管家婆软件 编辑:程序博客网 时间:2024/05/16 05:50

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].

思路:这题有很多种方法。自己写了一种,主要就是先把5、6、7接到另一个vector上,再把剩下的接上去,但这样不太符合O(1) space的要求

(我不管!反正是我自己写的!我就要贴!)

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

以下是两种个人觉得很帅的方法:

以下代码并不能通过Leetcode的编译,可能是因为Leetcode现在不能用这些函数了。

1、先逆转n-k到n的部分,再逆转1到n-k-1的部分,最后整体逆转。

class Solution {public:    void rotate(vector<int>& nums, int k) {        int n=nums.size();        while(k>n)k%=n;            // Reverse the first n - k numbers.            // Index i (0 <= i < n - k) becomes n - k - i.            reverse(nums, nums[n-k-1]);            // Reverse tha last k numbers.            // Index n - k + i (0 <= i < k) becomes n - i.            reverse(nums[n-k-1], nums[n-1]);            // Reverse all the numbers.            // Index i (0 <= i < n - k) becomes n - (n - k - i) = i + k.            // Index n - k + i (0 <= i < k) becomes n - (n - i) = i.            reverse(nums, nums[n-1]);    }};
2、先交换前K个和后K个,然后范围缩小进一步交换(并没有看太懂不过觉得很酷)

class Solution {public:    void rotate(int nums[], int n, int k)     {        for (; k = k%n; n -= k, nums += k)        {            // Swap the last k elements with the first k elements.             // The last k elements will be in the correct positions            // but we need to rotate the remaining (n - k) elements             // to the right by k steps.            for (int i = 0; i < k; i++)            {                swap(nums[i], nums[n - k + i]);            }        }    }};



0 0
原创粉丝点击