天天看點

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

繼續閱讀