題目描述
在這個題目,您可以對清單做以下操作:
在指定索引位置插入元素:
Insert
x y
x y
移除指定索引位置的元素:
Delete
x
x
給定一個整數的清單,要對這個清單做一些操作。一旦完成所有的操作,輸出修改過後的清單,用空格字元分隔每個清單中的整數。
原題網址
輸入格式
第一行為一個整數N,表示清單一開始的整數元素數量。範圍在1到4000之間(包含1和4000)。
第二行有N個整數,使用空格隔開,為清單一開始所包含的整數元素。
第三行為一個整數Q,表示要對清單操作的次數。範圍在1到4000之間(包含1和4000)。
接下來的2Q行的格式,每兩行為一個操作,格式請見題目描述。
輸出格式
輸出修改過後的清單,用空格字元分隔每個清單中的整數。
範例輸入
5
12 0 1 78 12
2
Insert
5 23
Delete
0
12 0 1 78 12
2
Insert
5 23
Delete
0
範例輸出
0 1 78 12 23
額外解釋
清單為 [12, 0, 1, 78 , 12]
第一次操作將23插入索引5的位置。
清單為 [12, 0, 1, 78 , 12, 23]
第二次操作將索引0的位置的元素刪除。
清單為 [0, 1, 78 , 12, 23]
解題概念
利用Java內建的ArrayList類別來建構出清單。ArrayList物件的add方法對應「Insert」操作,而remove則是對應「Delete」操作。
參考答案
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
final Scanner sc = new Scanner(System.in);
final int N = sc.nextInt();
final ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < N; ++i) {
list.add(sc.nextInt());
}
final int Q = sc.nextInt();
for (int i = 0; i < Q; ++i) {
sc.nextLine(); // skip
final String type = sc.nextLine();
switch (type) {
case "Insert": {
final int index = sc.nextInt();
final int value = sc.nextInt();
list.add(index, value);
}
break;
case "Delete": {
final int index = sc.nextInt();
list.remove(index);
}
break;
}
}
final StringBuilder sb = new StringBuilder();
for (final int value : list) {
sb.append(value).append(" ");
}
System.out.println(sb.toString().trim());
}
}