📜  用于分隔数组中的 0 和 1 的Python程序

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

用于分隔数组中的 0 和 1 的Python程序

你会得到一个随机排列的 0 和 1 数组。将数组左侧的 0 和右侧的 1 分隔开。仅遍历数组一次。

Input array   =  [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
Output array =  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 

方法 1(计数 0 或 1)
感谢 Naveen 提出这种方法。
1) 计算 0 的个数。设计数为 C。
2)一旦我们有了计数,我们可以把C个0放在数组的开头,把1放在数组中剩余的n-C个位置。
时间复杂度: O(n)

输出 :

Array after segregation is 0 0 1 1 1 1 

方法1遍历数组两次。方法 2 在单遍中执行相同的操作。

方法二(使用两个索引进行遍历)
维护两个索引。将左侧的第一个索引初始化为 0,将右侧的第二个索引初始化为 n-1。
left < right时执行以下操作
a) 当有 0 时,保持向左递增索引
b) 当有 1 时,保持正确的递减索引
c) 如果 left < right 然后交换 arr[left] 和 arr[right]

执行:

Python
# Python program to sort a binary array in one pass
  
# Function to put all 0s on left and all 1s on right
def segregate0and1(arr, size):
    # Initialize left and right indexes
    left, right = 0, size-1
      
    while left < right:
        # Increment left index while we see 0 at left
        while arr[left] == 0 and left < right:
            left += 1
  
        # Decrement right index while we see 1 at right
        while arr[right] == 1 and left < right:
            right -= 1
  
        # If left is smaller than right then there is a 1 at left
        # and a 0 at right. Exchange arr[left] and arr[right]
        if left < right:
            arr[left] = 0
            arr[right] = 1
            left += 1
            right -= 1
  
    return arr
  
# driver program to test
arr = [0, 1, 0, 1, 1, 1]
arr_size = len(arr)
print("Array after segregation")
print(segregate0and1(arr, arr_size))
  
# This code is contributed by Pratik Chhajer


输出:

Array after segregation is 0 0 1 1 1 1 

时间复杂度: O(n)

另一种方法:
1. 取两个指针 type0(对于元素 0)从头开始(索引 = 0)和 type1(对于元素 1)从尾开始(索引 = array.length-1)。
初始化 type0 = 0 和 type1 = array.length-1
2. 打算把 1 放到数组的右边。一旦完成,那么 0 肯定会朝向数组的左侧。

输出:

Array after segregation is 0 0 1 1 1 1 

时间复杂度: O(n)
有关详细信息,请参阅有关在数组中隔离 0 和 1 的完整文章!