import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
int x = scanner.nextInt();
int y = scanner.nextInt();
int[] pos = new int[n + 1];
for (int i = 0; i < n; i++) {
pos[a[i]] = i;
}
int px = pos[x];
int py = pos[y];
if (Math.abs(px - py) == 1) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
https://www.nowcoder.com/discuss/727521113110073344
思路:
- 读取输入:使用
Scanner读取输入数据。首先读取排列的长度n,然后读取排列的元素数组a,最后读取需要判断的两个元素x和y。 - 记录位置:创建一个
pos数组,其中pos[value]表示元素value在排列中的索引位置。遍历排列数组a,将每个元素的位置记录在pos数组中。 - 判断相邻:通过查询
pos数组获取x和y的位置,计算它们的差值绝对值。如果差值为1,则输出"Yes",否则输出"No"。



京公网安备 11010502036488号