在 Python 中移动零

pythonserver side programmingprogramming更新于 2025/10/31 8:44:17

假设我们有一个数组来保存一些数字。其中既有非零值,也有零值。因此,我们必须将所有零发送到右侧,而不改变其他数字的相对顺序。因此,如果数组为 [0, 1, 5, 0, 3, 8, 0, 0, 9],则最终数组将为 [1, 5, 3, 8, 9, 0, 0, 0, 0]

要解决这个问题,我们将遵循以下步骤 −

  • 假设 index = 0
  • 对于 i = 0 到 A 的长度
    • 如果 A[i] != 0,则
      • A[index] := A[i]
      • index := index + 1
  • 对于 i = index 到 A 的长度
    • A[i] = 0

示例

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

class Solution(object):
   def moveZeroes(self, nums):
      """
      :type nums: List[int]
      :rtype: None Do not return anything, modify nums in-place instead.
      """
      insert_index = 0
      for i in range(len(nums)):
         if nums[i] != 0:
            nums[insert_index]=nums[i]
            insert_index+=1
      for i in range(insert_index,len(nums)):
         nums[i]=0
nums = [0,1,5,0,3,8,0,0,9]
ob1 = Solution()
ob1.moveZeroes(nums)
print(nums)

输入

nums = [0,1,5,0,3,8,0,0,9]

输出

[1,5,3,8,9,0,0,0,0]

相关文章


有用资源