标签:思路 旋转 说明 app modify def 旋转数组 一个 解决
问题:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的原地算法。
class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        long = len(nums)
        newk= k % long
        temp = []
        for i in range(long):
            temp.append(nums[i-newk])
        for j in range(long):
            nums[j] = temp[j]
解题思路:
数组无论怎样移动,元素之间的顺序是不会变得,只要找到最后的状态即可;
使用一个空数组 temp = [] 保存 nums移动后的状态,然后一对一复制过去即可。
标签:思路 旋转 说明 app modify def 旋转数组 一个 解决
原文地址:https://www.cnblogs.com/wangjunget/p/9739941.html