给定一个随机排列的 0 和 1 数组,您需要将数组中的 0 和 1 分开。 例如:
arr[] = {0,1,0,0,1,1,1,0,1} Array after separating odd and even numbers : {0,0,0,0,1,1,1,1,1}
解决方案1: 计算数组中 0 的数量。假设我们得到 X 0 一旦我们得到计数,将 X 0 放入数组,并将 (nX) 1 放入数组的后半部分。 java代码:
X 0
(nX) 1
public static int[] separate0s1sSolution1(int arr[]) { int count=0; for (int i = 0; i < arr.length; i++) { if(arr[i]==0) { count++; } } for (int i = 0; i < count; i++) { arr[i]=0; } for (int i = count; i < arr.length; i++) { arr[i]=1; } return arr; }
时间复杂度:O(N) 解决方案2: 算法:
让我们说数组是 arr[]
left=0 和 right=arr.length-1
1
left < right
arr[left]
arr[right]
java代码:
public static int[] separate0s1sSolution2(int arr[]) { for (int i = 0; i < arr.length; i++) { int left=0; int right=arr.length-1; while(arr[left]==0) { left++; } while(arr[right]==1) { right--; } if(left<right) { int temp=arr[left]; arr[left]=arr[right]; arr[right]=temp; } } return arr; }
用于分隔数组中奇数和偶数的 Java 代码:
package org.arpit.java2blog; public class Separate0s1sMain { public static void main(String[] args) { int arr[]={0,1,0,0,1,1,1,0,1}; System.out.println("Original Array: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } arr=separate0s1sSolution1(arr); System.out.println("n==========================="); System.out.println("Solution 1"); System.out.println("nArray after separating 0's and 1's : "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } System.out.println("n==========================="); System.out.println("Solution 2"); arr=separate0s1sSolution2(arr); System.out.println("nArray after separating 0's and 1's : "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } public static int[] separate0s1sSolution1(int arr[]) { int count=0; for (int i = 0; i < arr.length; i++) { if(arr[i]==0) { count++; } } for (int i = 0; i < count; i++) { arr[i]=0; } for (int i = count; i < arr.length; i++) { arr[i]=1; } return arr; } public static int[] separate0s1sSolution2(int arr[]) { for (int i = 0; i < arr.length; i++) { int left=0; int right=arr.length-1; while(arr[left]==0) { left++; } while(arr[right]==1) { right--; } if(left<right) { int temp=arr[left]; arr[left]=arr[right]; arr[right]=temp; } } return arr; } }
当你运行上面的程序时,你会得到以下输出:
Original Array: 0 1 0 0 1 1 1 0 1 =========================== Solution 1 Array after separating 0's and 1's : 0 0 0 0 1 1 1 1 1 =========================== Solution 2 Array after separating 0's and 1's : 0 0 0 0 1 1 1 1 1