Java 中將所有零移到陣列末尾


在 Java 中,陣列是一個物件。它是一種非原始資料型別,用於儲存相同資料型別的值。

根據問題陳述,我們必須將所有零移到陣列的末尾,即如果陣列包含 n 個零,則所有 n 個零都將被推送到陣列的末尾。

讓我們探索本文,看看如何使用 Java 程式語言來實現。

展示一些示例

示例 1

假設原始陣列為 {128, 0, 99, 67, 50, 0, 29, 7, 0}

將所有零移到陣列末尾後的結果將是

將所有零移到陣列末尾後的陣列元素

128 99 67 50 29 7 0 0 0

示例 2

假設原始陣列為 {23, 9, 6, 4, 0, 0, 21, 7, 0, 6, 0, 9}

將所有零移到陣列末尾後的結果將是

將所有零移到陣列末尾後的陣列元素

23 9 6 4 21 7 6 9 0 0 0 0

示例 3

假設原始陣列為 {3, 9, 5, 1, 0, 0, 11, 6, 0, 9}

將所有零移到陣列末尾後的結果將是

將所有零移到陣列末尾後的陣列元素

3 9 5 1 11 6 9 0 0 0

演算法

演算法 1(使用排序)

  • 步驟 1 - 宣告並初始化一個整數陣列。

  • 步驟 2 - 實現多種方法的邏輯。

  • 步驟 3 - 按降序對陣列進行排序,因此零將位於最後一個位置。

  • 步驟 4 - 列印陣列的元素。

演算法 2(透過手動迭代和替換)

  • 步驟 1 - 宣告並初始化一個整數陣列。

  • 步驟 2 - 實現多種方法的邏輯。

  • 步驟 3 - 將所有非零元素推送到陣列的左側,零元素保留在末尾。

  • 步驟 4 - 列印陣列的元素。

語法

要獲取陣列的長度(該陣列中的元素數量),陣列有一個內建屬性,即 length

下面是其語法:

array.length

其中,'array' 指的是陣列引用。

多種方法

我們提供了不同方法的解決方案。

  • 使用排序

  • 透過手動迭代和替換

讓我們逐一檢視程式及其輸出。

方法 1:使用排序

在這種方法中,陣列元素將在程式中初始化。然後根據演算法按降序對陣列進行排序,因此零將位於最後一個位置。

示例

import java.util.*;
public class Main {
   public static void main(String[] args){
      
      //Declare and initialize the array elements
      int array[] = {128, 0, 99, 67, 50, 0, 29, 7, 0};
      
      //getting length of an array
      int n = array.length;
      
      //calling user defined function
      func(array, n);
   }
   
   //user defined method
   public static void func(int array[], int n) {
   
      //sorting the array elements
      Arrays.sort(array);
      System.out.println("Elements of array after moving all the zeros to the end of array: ");
      
      //prints array using the for loop
      for (int i = n-1; i >= 0; i--) {
         System.out.print(array[i] + " ");
      }
   }
}

輸出

Elements of array after moving all the zeros to the end of array: 
128 99 67 50 29 7 0 0 0 

方法 2:透過手動迭代和替換

在這種方法中,陣列元素將在程式中初始化。然後根據演算法將所有非零元素推送到陣列的左側,零元素保留在末尾。

示例

import java.io.*;
public class Main {
   public static void main (String[] args){
       
      //Declare and initialize the array elements
      int arr[] = {3, 9, 5, 1, 0, 0, 11, 6, 0, 9};
      
      //getting length of an array
      int n = arr.length;
      
      //calling user defined method
      func(arr, n);
   }
   
   //user defined method
   static void func(int arr[], int n) {
      // Count of non-zero elements
      int count = 0;
      
      //shifting non zero element to the left of the loop
      for (int i = 0; i < n; i++)
      if (arr[i] != 0)
      arr[count++] = arr[i];
      
      //adding the zeros to the end
      while (count < n)
      arr[count++] = 0;
      
      //printing the result
      System.out.println("Elements of array after moving all the zeros to the end of array: ");
      for (int i = 0; i < n; i++)
      System.out.print(arr[i] + " ");
   }
}

輸出

Elements of array after moving all the zeros to the end of array: 
3 9 5 1 11 6 9 0 0 0

在本文中,我們探討了如何使用 Java 程式語言將所有零移到陣列的末尾。

更新於: 2023 年 2 月 2 日

12K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.