问题描述
小C拿到了一个排列,她想知道在这个排列中,元素 xx 和 yy 是否是相邻的。排列是一个长度为 nn 的数组,其中每个数字从 11 到 nn 恰好出现一次。
你的任务是判断在给定的排列中,xx 和 yy 是否是相邻的。
测试样例
样例1:
输入:
n = 4, a = [1, 4, 2, 3], x = 2, y = 4
输出:True
样例2:
输入:
n = 5, a = [3, 4, 5, 1, 2], x = 3, y = 2
输出:False
样例3:
输入:
n = 6, a = [6, 1, 5, 2, 4, 3], x = 5, y = 2
输出:True
解题思路
由于排列是一个数组,我们可以直接使用数组来存储和操作数据。
算法步骤
- 遍历数组:从数组的第一个元素开始,遍历到倒数第二个元素。
- 检查相邻元素:对于每个元素,检查它和它的下一个元素是否分别是
x和y,或者y和x。 - 返回结果:如果在遍历过程中找到相邻的
x和y,则返回true;如果遍历结束仍未找到,则返回false。
代码
public class Main {
public static boolean solution(int n, int[] a, int x, int y) {
// 遍历数组
for (int i = 0; i < n - 1; i++) {
// 检查当前元素和下一个元素是否分别是 x 和 y,或者 y 和 x
if ((a[i] == x && a[i + 1] == y) || (a[i] == y && a[i + 1] == x)) {
// 如果找到相邻的 x 和 y,返回 true
return true;
}
}
// 如果遍历结束仍未找到,返回 false
return false;
}
public static void main(String[] args) {
System.out.println(solution(4, new int[]{1, 4, 2, 3}, 2, 4) == true);
System.out.println(solution(5, new int[]{3, 4, 5, 1, 2}, 3, 2) == false);
System.out.println(solution(6, new int[]{6, 1, 5, 2, 4, 3}, 5, 2) == true);
}
}
优化方案
-
减少不必要的比较:
- 当前代码在每次循环中都进行了两次比较(
a[i] == x && a[i + 1] == y和a[i] == y && a[i + 1] == x)。实际上,如果x和y是相邻的,那么在一次比较中就会找到结果。 - 可以考虑在找到相邻的
x和y后立即返回true,而不需要继续遍历。
- 当前代码在每次循环中都进行了两次比较(
-
边界条件处理:
- 当前代码在遍历到
n-1时结束,因为i+1不能越界。这个处理是正确的,但可以考虑在代码中明确指出这一点。
- 当前代码在遍历到
-
代码可读性:
- 可以通过添加注释来提高代码的可读性,特别是在关键步骤和边界条件处理的地方。
public class Main {
public static boolean solution(int n, int[] a, int x, int y) {
// 遍历数组,注意边界条件
for (int i = 0; i < n - 1; i++) {
// 检查当前元素和下一个元素是否分别是 x 和 y,或者 y 和 x
if ((a[i] == x && a[i + 1] == y) || (a[i] == y && a[i + 1] == x)) {
// 如果找到相邻的 x 和 y,立即返回 true
return true;
}
}
// 如果遍历结束仍未找到,返回 false
return false;
}
public static void main(String[] args) {
System.out.println(solution(4, new int[]{1, 4, 2, 3}, 2, 4) == true);
System.out.println(solution(5, new int[]{3, 4, 5, 1, 2}, 3, 2) == false);
System.out.println(solution(6, new int[]{6, 1, 5, 2, 4, 3}, 5, 2) == true);
}
}