算法每一题,成长每一天~
C0E25 最小的调整次数 / 特异性双端队列
真题链接:【持续更新】2024华为 OD 机试E卷 机考真题库清单(全真题库)
思路
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class C0E25 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
// 用一个队列来记录命令
Queue<String> cmd = new LinkedList<>();
for (int i = 0; i < 2 * n; i++) {
cmd.offer(in.nextLine());
}
boolean sort = true; // 顺序OK
int change = 0; // 顺序改变次数
// 用一个列队来入队出队
Queue<Integer> queue = new LinkedList<>();
while (!cmd.isEmpty()) {
String curCmd = cmd.poll();
if (!queue.isEmpty()
&& curCmd.startsWith("head")) {
// 头部放入,且队列不为空,则顺序出错
sort = false;
}
if (curCmd.equals("remove")) {
if (!sort) {
// 拿出时,顺序不对,则需要改变一次顺序
change++;
sort = true;
}
queue.poll(); // 拿出一个元素
} else {
queue.offer(1); // 这里并不需要关心怎么放入,放入的是什么
}
}
System.out.println(change);
}
}
总结
1、纯逻辑分析题,没什么特别的
算法要多练多练多练!!