例如输入:
3
head add 1
remove
tail add 2
head add 3
remove
remove
输出:
1
说明:
解题思路:使用双向的队列近行存储,利于排序,从头插入,从尾插入
java 参考代码如下:
Scanner in = new Scanner(System.in);
// 最小的调整次数
while (in.hasNextInt()) {
LinkedList<Integer> list = new LinkedList<>();
int n = in.nextInt();
// 回车
in.nextLine();
int operations = 2 * n;
LinkedList<String> operationList = new LinkedList<>();
for (int i = 0; i < operations; i++) {
String str = in.nextLine();
operationList.add(str);
}
int index = 1;
int count = 0;
for (var operation : operationList) {
String[] strs = operation.split(" ");
if (strs.length == 1) {
if (list.get(0) != index) {
Collections.sort(list);;
count++;
}
list.removeFirst();
index ++;
} else {
if (strs[0].equals("head")) {
list.addFirst(Integer.valueOf(strs[2]));
} else {
list.addLast(Integer.valueOf(strs[2]));
}
}
}
System.out.println(count);
}
至于细节方面,可以再优化一下,但是主要解题思路就是上面代码所示