首页 > 解决方案 > 为什么底部 for 循环不包含最后一个元素?

问题描述

问题:给定一个数组,将数组向右旋转 k 步,其中 k 是非负数。

示例:输入:nums = [1,2,3,4,5,6,7], k = 3 输出:[5,6,7,1,2,3,4]

我试过这样做:

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        x = nums
        for i in range(0, k):
            temp = []
            temp += [x.pop()]
            for i in  range(0, len(x)):
                temp += [x[i]]
            x = temp
     
        for i in range(0, len(nums)):
            nums[i] = x[i]
   
        

我只得到 [5,6,7,1,2,3] 的输出,我不知道为什么最后一个元素,即 4 被切掉,即使我在尝试打印 x 时看到它。

信用:这是一个 leetcode 问题

标签: arraysfor-looprotation

解决方案


我看到您正在尝试通过 x = nums 复制您的 nums,但这不是 python 的工作方式(其他语言可能不同)。您在 x 上应用的任何内容也适用于 nums。由于您使用的是 x.pop(),因此 nums 数组也会不可逆地缩小。为了制作 nums 的副本,您可以使用 nums[:]。我更改了您的代码,现在可以使用。(也在 leetcode 上运行)

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        x = nums[:]
        for i in range(0, k):
            temp = []
            temp += [x.pop()]
            for i in  range(0, len(x)):
                temp += [x[i]]
            x = temp
     
        for i in range(0, len(nums)):
            nums[i] = x[i]

推荐阅读