题解 | 【模板】序列操作
【模板】序列操作
https://www.nowcoder.com/practice/12da4185c0bb45918cfdc3072e544069
思路
数据结构模拟题。
根据题意进行模拟操作,可以将每次输入当成数字进行处理,然后根据每次操作输入的第一个数判断是什么操作,跳转到不同操作内部,进行操作,用到了switch操作。
这里使用Integer数组进行维护。由于操作4 i x表示在元素i和元素i + 1的元素之间插入整数x,这里需要用链表方便吗?怎么处理这种插入操作呢?实际上不用,直接使用Java的ArrayList实现add操作接口。
import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
while (q-- > 0) {
// 接收每次操作的第一个数
int oper = sc.nextInt();
switch(oper) {
case 1:
// 向末尾增加一个整数x
int x = sc.nextInt();
arr.add(x);
break;
case 2:
// 删除末尾元素
// 检查非空
if (!arr.isEmpty()) {
arr.remove(arr.size() - 1);
}
break;
case 3:
// 输出序列中下标i的元素
int i = sc.nextInt();
System.out.println(arr.get(i));
break;
case 4:
// 在下标i和下标i+1之间插入整数x
int idx = sc.nextInt();
int val = sc.nextInt();
if (idx >= 0 && idx <= arr.size()) {
arr.add(idx+1, val);
}
break;
case 5:
// 从小到大升序排序
Collections.sort(arr);
break;
case 6:
// 从大到校排序
Collections.sort(arr, Collections.reverseOrder());
break;
case 7:
// 输出当前序列的长度
System.out.println(arr.size());
break;
case 8:
// 输出当前整个序列
for (int j = 0; j < arr.size(); j++) {
System.out.print(arr.get(j));
if (j < arr.size() - 1) {
System.out.print(" ");
}
}
System.out.println(); // 换行
break;
default:
break;
}
}
sc.close();
}
}
顺丰集团工作强度 420人发布