Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
rotate-array.py 2.52 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 13:04 +08:00 . update
# Time: O(n)
# Space: O(1)
class Solution(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
k %= len(nums)
self.reverse(nums, 0, len(nums))
self.reverse(nums, 0, k)
self.reverse(nums, k, len(nums))
def reverse(self, nums, start, end):
while start < end:
nums[start], nums[end - 1] = nums[end - 1], nums[start]
start += 1
end -= 1
# Time: O(n)
# Space: O(1)
from fractions import gcd
class Solution2(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
def apply_cycle_permutation(k, offset, cycle_len, nums):
tmp = nums[offset]
for i in xrange(1, cycle_len):
nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)]
nums[offset] = tmp
k %= len(nums)
num_cycles = gcd(len(nums), k)
cycle_len = len(nums) / num_cycles
for i in xrange(num_cycles):
apply_cycle_permutation(k, i, cycle_len, nums)
# Time: O(n)
# Space: O(1)
class Solution3(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
count = 0
start = 0
while count < len(nums):
curr = start
prev = nums[curr]
while True:
idx = (curr + k) % len(nums)
nums[idx], prev = prev, nums[idx]
curr = idx
count += 1
if start == curr:
break
start += 1
# Time: O(n)
# Space: O(n)
class Solution4(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k]
# Time: O(k * n)
# Space: O(1)
class Solution5(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
while k > 0:
nums.insert(0, nums.pop())
k -= 1
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助