您如何使用Java在整数数组中将零与非零分开?

要在整数数组中将零与非零分开并将其推到末尾,您需要通过从零开始按顺序分配所有非零元素到其位置来重新排列其数组。然后,从数组的最后一个位置到其末尾填充零。

示例

随后的Java程序将数组中的所有零推到末尾。

import java.util.Arrays;
import java.util.Scanner;
public class ZerosFromNonZeros {
   public static void main(String args[]){
      //从用户读取数组
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is: "+Arrays.toString(myArray));
      System.out.println("Resultant array: ");
      int pos = 0;
      for(int i=0; i<myArray.length; i++){
         if(myArray[i]!=0){
            myArray[pos]=myArray[i];
            pos++;
         }
      }
      while(pos<myArray.length) {
         myArray[pos] = 0;
         pos++;
      }
      System.out.println("The array created is: "+Arrays.toString(myArray));
   }
}

输出结果

Enter the size of the array that is to be created:
8
Enter the elements of the array:
14
0
56
0
12
47
0
0
The array created is: [14, 0, 56, 0, 12, 47, 0, 0]
Resultant array:
The array created is: [14, 56, 12, 47, 0, 0, 0, 0]

以相同的方式将零放置在数组的开头,向后迭代数组的元素,从最后一个位置开始依次排列数组中的每个非零元素。最后,用零填充其余位置。

通过从零开始按顺序分配所有非零元素到其位置来重新排列它的数组。然后,从数组的最后一个位置到其末尾填充零。

示例

随后的Java程序将数组中的所有零推到开头。

import java.util.Arrays;
import java.util.Scanner;
public class ZerosFromNonZeros {
   public static void main(String args[]){
      //从用户读取数组
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is: "+Arrays.toString(myArray));
      System.out.println("Resultant array: ");
      int pos = myArray.length-1;
      for(int i = myArray.length-1; i>=0; i--){
         if(myArray[i]!=0){
            myArray[pos]=myArray[i];
            pos--;
         }
      }
      while(pos>=0) {
         myArray[pos] = 0;
         pos--;
      }
      System.out.println("The array created is: "+Arrays.toString(myArray));
   }
}

输出结果

Enter the size of the array that is to be created:
8
Enter the elements of the array:
14
0
56
0
12
47
0
0
The array created is: [14, 0, 56, 0, 12, 47, 0, 0]
Resultant array:
The array created is: [0, 0, 0, 0, 14, 56, 12, 47]