-
遍历数组:你需要遍历数组
a,检查相邻的两个元素是否分别是x和y。 -
检查相邻元素:在遍历过程中,检查当前元素和下一个元素是否分别是
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; } } // 如果遍历完整个数组都没有找到相邻的 x 和 y,返回 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); } }
-
遍历数组:使用
for循环遍历数组a,注意循环的范围是0到n-2,因为我们只需要检查到倒数第二个元素。 -
检查相邻元素:在循环中,使用
if语句检查当前元素a[i]和下一个元素a[i + 1]是否分别是x和y,或者y和x。 -
返回结果:如果找到相邻的
x和y,则返回true;如果遍历完整个数组都没有找到,则返回false。