小C的排列询问

67 阅读1分钟
  1. 遍历数组:你需要遍历数组 a,检查相邻的两个元素是否分别是 x 和 y

  2. 检查相邻元素:在遍历过程中,检查当前元素和下一个元素是否分别是 x 和 y,或者 y 和 x

  3. 返回结果:如果在遍历过程中找到了相邻的 x 和 y,则返回 true;如果遍历完整个数组都没有找到,则返回 false

  4. 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); } }

  5. 遍历数组:使用 for 循环遍历数组 a,注意循环的范围是 0 到 n-2,因为我们只需要检查到倒数第二个元素。

  6. 检查相邻元素:在循环中,使用 if 语句检查当前元素 a[i] 和下一个元素 a[i + 1] 是否分别是 x 和 y,或者 y 和 x

  7. 返回结果:如果找到相邻的 x 和 y,则返回 true;如果遍历完整个数组都没有找到,则返回 false