用于在数组中分离 0 和 1 的 Python3 程序
你会得到一个随机排列的 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)
Python3
# Python 3 code to Segregate
# 0s and 1s in an array
# Function to segregate 0s and 1s
def segregate0and1(arr, n) :
# Counts the no of zeros in arr
count = 0
for i in range(0, n) :
if (arr[i] == 0) :
count = count + 1
# Loop fills the arr with 0 until count
for i in range(0, count) :
arr[i] = 0
# Loop fills remaining arr space with 1
for i in range(count, n) :
arr[i] = 1
# Function to print segregated array
def print_arr(arr , n) :
print( "Array after segregation is ",end = "")
for i in range(0, n) :
print(arr[i] , end = " ")
# Driver function
arr = [ 0, 1, 0, 1, 1, 1 ]
n = len(arr)
segregate0and1(arr, n)
print_arr(arr, n)
# This code is contributed by Nikita Tiwari.
Python3
# 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):
type0 = 0
type1 = size - 1
while(type0 < type1):
if(arr[type0] == 1):
(arr[type0],
arr[type1]) = (arr[type1],
arr[type0])
type1 -= 1
else:
type0 += 1
# Driver Code
arr = [0, 1, 0, 1, 1, 1]
arr_size = len(arr)
segregate0and1(arr, arr_size)
print("Array after segregation is",
end = " ")
for i in range(0, arr_size):
print(arr[i], end = " ")
# This code is contributed
# by Shivi_Aggarwal
输出 :
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]
执行:
输出:
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 肯定会朝向数组的左侧。
Python3
# 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):
type0 = 0
type1 = size - 1
while(type0 < type1):
if(arr[type0] == 1):
(arr[type0],
arr[type1]) = (arr[type1],
arr[type0])
type1 -= 1
else:
type0 += 1
# Driver Code
arr = [0, 1, 0, 1, 1, 1]
arr_size = len(arr)
segregate0and1(arr, arr_size)
print("Array after segregation is",
end = " ")
for i in range(0, arr_size):
print(arr[i], end = " ")
# This code is contributed
# by Shivi_Aggarwal
输出:
Array after segregation is 0 0 1 1 1 1
时间复杂度: O(n)
有关详细信息,请参阅有关在数组中隔离 0 和 1 的完整文章!