如何使用 Java 从整数数组中分离零和非零元素?


若要从整数数组中分离零和非零元素并将零移动到尾部,需要按以下顺序重新排列数组:将所有非零元素依次指定给其位置,从零开始。然后,从数组的最后一个位置到其尾部填充零。

示例

以下 Java 程序将数组中的所有零移到尾部。

import java.util.Arrays;
import java.util.Scanner;
public class ZerosFromNonZeros {
   public static void main(String args[]){
      //Reading the array from the user
      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[]){
      //Reading the array from the user
      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]

更新于: 02-Aug-2019

2K+ 浏览

开启 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.