如何使用 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.