• Java 資料結構教程

從陣列中移除元素



要從陣列中移除現有元素,需要跳過給定位置(例如 k)的元素,將其替換為下一個元素(k+1),然後將 k+1 位置的元素替換為 k+2 位置的元素,以此類推,直到陣列末尾。最後忽略最後一個元素。

演算法

假設 LA 是一個包含 N 個元素的線性陣列,K 是一個正整數,且 K<=N。以下是刪除 LA 中第 K 個位置的元素的演算法。

Step 1 - Start
Step 2 - Set J = K
Step 3 - Repeat steps 4 and 5 while J < N
Step 4 - Set LA[J] = LA[J + 1]
Step 5 - Set J = J+1
Step 6 - Set N = N-1
Step 7 - Stop

示例

public class RemovingElements {
   public static void main(String args[]) {
      int[] myArray = {10, 20, 30, 45, 96, 66};
      
      int pos = 3;
      int j = myArray.length;
      
      for(int i = pos; i < j-1; i++) {
         myArray[i] = myArray[i+1];
      }        

      System.out.println("Contents of the array after deletion ::");   
      for(int i = 0; i < myArray.length-1; i++) {
         System.out.print(myArray[i]+ ", ");
      }   
   }
}

輸出

Contents of the array after deletion ::
10, 20, 30, 96, 66,

ArrayUtils 類提供 remove() 方法來從陣列中刪除元素。

示例

import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;

public class RemovingElements {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number of elements needed :");
      int n = sc.nextInt();
      int[] myArray = new int[n];
      System.out.println("Enter the elements ::");
      
      for(int i = 0; i < n; i++) {
         myArray[i] = sc.nextInt();
      }        
      
      System.out.println("Enter the position to delete the element :");
      int pos = sc.nextInt();
      
      int [] result = ArrayUtils.remove(myArray, pos);
      System.out.println("Contents of the array after deletion ::");
   
      for(int i = 0; i < result.length; i++) {
         System.out.print(result[i]+ " ");
      }
   }
}

輸出

Enter the number of elements needed :
5
Enter the elements ::
44
55
62
45
55
Enter the position to delete the element :
3
Contents of the array after deletion ::
44 55 62 55
廣告
© . All rights reserved.