场景或问题陈述:
这是元旦,每个人都在排队参加仙境过山车!有很多人在排队,每个人都戴着一个贴纸,表明他们在队列中的初始位置。初始位置从行前面的 1 到后面的 n 递增 1。
队列中的任何人都可以贿赂直接排在他们前面的人以交换位置。如果两个人交换位置,他们仍然会佩戴相同的标签,表示他们原来的位置。一个人最多可以贿赂另外两个人。例如,如果 n = 8 并且第 5 个人贿赂第 4 个人,则队列将如下所示:1,2,3,5,4,6,7,8。
对这个混乱的队列着迷,您决定必须知道为使队列进入当前状态而发生的最低贿赂次数!
功能说明
在下面的编辑器中完成函数 minimumBribes。它必须打印一个整数,表示必要的最低贿赂数量,或者如果线路配置不可能,则太混乱。
minimumBribes 具有以下参数:
q:整数数组
输入格式
第一行包含一个整数,即测试用例的数量。
接下来的每一对行如下: - 第一行包含一个整数,即队列中的人数 - 第二行包含以空格分隔的整数,描述队列的最终状态。
输出格式
打印一个整数,表示使队列进入最终状态所需的最小贿赂数。打印状态无效时太乱,即要求人贿赂人多。
样本输入
2
8
5 1 2 3 7 8 6 4
8
1 2 5 3 7 8 6 4
样本输出
Too chaotic
7
我基本上是在尝试创建一个方法,该方法在此(最终)状态下接受队列的值,并返回从 1、2、3、4、5、... 开始到达最终状态所需的贿赂数量。状态,如果队列中每人的贿赂数量不超过 2,否则“太混乱”。
使用 java 流在少数情况下失败的代码如下,我想知道为什么我无法使用 Java 流实现输出?
static void minimumBribes(int[] q) {
AtomicInteger bribeCount = new AtomicInteger(0);
AtomicReference<String> chaoticString = new AtomicReference<String>();
IntStream.rangeClosed(1, q.length).forEach(i -> {
if (q[i - 1] > i) {
if (q[i - 1] - i > 2) {
chaoticString.set("Too chaotic");
} else {
bribeCount.addAndGet(q[i - 1] - i);
}
}
});
if (chaoticString.get() == "Too chaotic")
System.out.print(chaoticString.get());
else
System.out.print(bribeCount.get());
}
不使用 java 流通过的代码如下:
static void minimumBribes(int[] q) {
for (int i = 0; i < q.length; i++) {
if (q[i] - (i + 1) > 2) {
System.out.println("Too chaotic");
return;
}
}
int bribe = 0;
for (int i = 0; i < q.length; i++) {
for (int j = i + 1; j < q.length; j++) {
if(q[i] > q[j]) {
q[j] = q[i] + q[j];
q[i] = q[j] - q[i];
q[j] = q[j] - q[i];
bribe++;
}
}
}
System.out.println(bribe);
}
public class MaximumTwoBribesAllowedForMovingForwardInQueue {
//Method that needs to be filled in
static void minimumBribes(int[] q) {
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int tItr = 0; tItr < t; tItr++) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] q = new int[n];
String[] qItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int qItem = Integer.parseInt(qItems[i]);
q[i] = qItem;
}
minimumBribes(q);
}
scanner.close();
}
}
如果有的话,你能帮忙推荐一些改变来用java流实现这个吗?
样本输入:
2
8
5 1 2 3 7 8 6 4
8
1 2 5 3 7 8 6 4
预期的正确输出:
Too chaotic
7
实际错误输出
Too chaotic
6