LeetCode-Rotate Array
发布日期:2021-08-31 01:31:18 浏览次数:2 分类:技术文章

本文共 1921 字,大约阅读时间需要 6 分钟。

hot3.png

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  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)的空间里完成这个呢?

根据大神 ,的方法确实做到了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,75,6,3,4,1,2,75,6,7,4,1,2,3---------n-=k==4 k%=n==35,6,7,1,4,2,35,6,7,1,2,4,35,6,7,1,2,3,4--------n-=k==1 k%=n==0DONE!!!
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

转载地址:https://blog.csdn.net/weixin_34056162/article/details/91923261 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Spring 异步线程池的使用
下一篇:Spring配置事务的五种方式

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年03月21日 20时31分08秒