如何使用 Java 将整数数组中的零和非零分开?

java 8object oriented programmingprogramming更新于 2025/9/20 11:56:17

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

示例

以下 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]

相关文章