LeetCode-Rotate Array

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.

Hint:
Could you do it in-place with O(1) extra space?

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.


这道题目比较简单,不过要考的是面试的时候能否想到尽可能多的算法并且具有空间和时间的高效性。

一开始想到一个空间O(1)的算法,但是明显太慢了,所以在遇到一个超长的测试数据时RLE了。这个空间O(1)的算法用的就是每次移动一格,这样子只需要一个临时数据就可以存储了。

class Solution {
public:
    void rotate(int nums[], int n, int k) {
        if (((k%=n) == 0)||n==1)return;
        int tmp;
        while(--k){
            rolling(nums,n);
        }
    }
    
    void rolling(int nums[], int n){
        int tmp = nums[--n];
        while(--n){
            nums[n+1] = nums[n];
        }
        nums[0] = tmp;
    }
};

另一种方法,用一个辅助的数组很容易就可以通过。

class Solution {
public:
    void rotate(int nums[], int n, int k) {
        if((k%=n)==0||n==1)return;
        int* tmp = new int[n];
        for(int i = k; i < n;++i)tmp[i] = nums[i-k];
        for(int i = 0; i < k;++i)tmp[i] = nums[n-k+i];
        for(int i = 0; i < n; ++i)nums[i] = tmp[i];
    }
};

题目要求想出至少3个方法,这才第一个。第二个方法比较逗,我了解到C++标准库里就有一个rotate函数,运算结果发现速度也不是特别快。

class Solution {
public:
    void rotate(int nums[], int n, int k) {
            if((k%=n)==0||n==1)return;
            std::rotate(nums,nums+n-k,nums+n);
    }
};

如何在O(1)的空间里完成这个呢?

根据大神 3 lines of C++ in one pass using swap,的方法确实做到了O(1)space,只是不太好理解。

按sample 1,2,3,4,5,6,7 -> 3 应该是 5,6,7,1,2,3,4,按照算法

5,2,3,4,1,6,7
5,6,3,4,1,2,7
5,6,7,4,1,2,3
---------n-=k==4 k%=n==3
5,6,7,1,4,2,3
5,6,7,1,2,4,3
5,6,7,1,2,3,4
--------n-=k==1 k%=n==0
DONE!!!
class Solution {
public:
    void rotate(int nums[], int n, int k) {
        for (; k %= n; n -= k)
            for (int i = 0; i < k; i++)
                swap(*nums++, nums[n - k]);
    }
};

其实一开始我也想到这样子,但是不知道如何有效地组织指针的移动,通过这个案例算是学到了不少。



转载于:https://my.oschina.net/xueyang/blog/383542

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值