从数组中移除元素
要从数组中移除现有元素,需要跳过给定位置(例如 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
广告