在 Python 中旋转数组

pythonserver side programmingprogramming更新于 2025/10/31 3:56:17

假设我们有一个数组 A。我们必须将其向右旋转 k 步。因此,如果数组为 A = [5, 7, 3, 6, 8, 1, 5, 4],且 k = 3,则输出将为 [1,5,4,5,7,3,6,8]。步骤如下

  • [4,5,7,3,6,8,1,5]
  • [5,4,5,7,3,6,8,1]
  • [1,5,4,5,7,3,6,8]

为了解决这个问题,我们将遵循以下步骤。

  • 设 n 为数组的大小
  • k = k mod n
  • A = 从 n – k 到结束的 A 子数组 + 从 0 到 n – k – 1 的 A 子数组

让我们看下面的实现,以便更好地理解 −

示例

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.
      """
      n = len(nums)
      k%=n
      nums[:] = nums[n-k:]+nums[:n-k]
nums = [5,7,3,6,8,1,5,4]
ob1 = Solution()
ob1.rotate(nums, 3)
print(nums)

输入

nums = [5,7,3,6,8,1,5,4]
k = 3

输出

[1,5,4,5,7,3,6,8]

相关文章


有用资源