【问题标题】:Why does the bottom for loop does not include last element?为什么底部 for 循环不包含最后一个元素?
【发布时间】:2021-04-05 16:53:29
【问题描述】:

问题:给定一个数组,将数组向右旋转 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 问题

【问题讨论】:

    标签: arrays for-loop rotation


    【解决方案1】:

    您的 nums 数组的大小正在缩小。它从7缩小到6,这不是我的 占主导地位的语言,所以我无法理解语法,因此我无法捕捉到错误。所以它比原始 x 数组的大小要小一。

    所以它永远不会到达 4 。

    我能想到的一种解决方法是在 :

    之后添加最后一个元素
    for i in range(0, len(nums)):
    nums[i] = x[i]
    
    nums.append(x[len(x)-1])
    

    【讨论】:

      【解决方案2】:

      我看到您正在尝试通过 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]
      

      【讨论】:

      • 感谢您的回答。我想知道我们如何才能克服时间超过错误。
      • 不客气!您需要优化算法的时间复杂度,例如您当前有两个嵌套的 for 循环,这会导致您的时间复杂度增加。看看您是否可以消除其中一个嵌套循环。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 2019-01-01
      • 1970-01-01
      • 2017-12-13
      • 2015-06-17
      相关资源
      最近更新 更多