题解 | #旋转数组#
旋转数组
https://www.nowcoder.com/practice/e19927a8fd5d477794dac67096862042
class Solution: def solve(self , n: int, m: int, a: List[int]) -> List[int]: # write code here m = m% n a.reverse() b = a[:m] b.reverse() c = a[m:] c.reverse() a[:m] = b a[m:] = c return a
解题思路
- 先整体翻转;
- 再翻转左边的前m个元素;
- 再翻转右边的n-m哥元素;
- 最后将这两个子数组拼起来,得到最终的结果。
复杂度
- 时间复杂度为O(N)
- 空间复杂度为O(N)。