📌  相关文章
📜  Python3程序将所有零移动到数组末尾| Set-2(使用单次遍历)

📅  最后修改于: 2022-05-13 01:54:20.739000             🧑  作者: Mango

Python3程序将所有零移动到数组末尾| Set-2(使用单次遍历)

给定一个包含n 个数字的数组。问题是将所有 0 移动到数组的末尾,同时保持其他元素的顺序。只需要对数组进行一次遍历。
例子:

Input : arr[]  = {1, 2, 0, 0, 0, 3, 6}
Output : 1 2 3 6 0 0 0

Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}
Output: 1 9 8 4 2 7 6 9 0 0 0 0 0

算法:

moveZerosToEnd(arr, n)
    Initialize count = 0
    for i = 0 to n-1
        if (arr[i] != 0) then
            swap(arr[count++], arr[i])

Python3
# Python implementation to move all zeroes at
# the end of array
  
# function to move all zeroes at
# the end of array
def moveZerosToEnd (arr, n):
  
    # Count of non-zero elements
    count = 0;
  
    # Traverse the array. If arr[i] is non-zero, then
    # swap the element at index 'count' with the
    # element at index 'i'
    for i in range(0, n):
        if (arr[i] != 0):
            arr[count], arr[i] = arr[i], arr[count]
            count+=1
  
  
# function to print the array elements
def printArray(arr, n):
  
    for i in range(0, n):
        print(arr[i],end=" ")
  
  
# Driver program to test above
arr = [ 0, 1, 9, 8, 4, 0, 0, 2,
    7, 0, 6, 0, 9 ]
n = len(arr)
  
print("Original array:", end=" ")
printArray(arr, n)
  
moveZerosToEnd(arr, n)
  
print("
Modified array: ", end=" ")
printArray(arr, n)
  
# This code is contributed by
# Smitha Dinesh Semwal


输出:

Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9 
Modified array: 1 9 8 4 2 7 6 9 0 0 0 0 0

时间复杂度:O(n)。
辅助空间:O(1)。

请参阅有关将所有零移到数组末尾的完整文章 | Set-2(使用单次遍历)了解更多详情!