天天看点

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

首先把数组复制一遍,然后找到元素之间的映射关系: <code>newnum[i] = oldnum[(i - k + n) % n]</code>,时间复杂度为<code>o(n)</code>,空间复杂度为<code>o(n)</code>。

将数组看成是一个环,每个元素每次往前走一步,循环<code>k</code>次。时间复杂度为<code>o(k*n)</code>,耗时较长,空间复杂度为<code>o(1)</code>。

①将整个数组反转

②将由分割点分割的两个数组分别反转

即:1 2 3 4 5 6 7 -&gt; 7 6 5 | 4 3 2 1 -&gt; 5 6 7 | 1 2 3 4

时间复杂度为<code>o(n)</code>,空间复杂度为<code>o(1)</code>。

继续阅读