CodeWars 서른 아홉 번째 문제

Updated:

Are they the “same”?

public static boolean comp(int[] a, int[] b) {

    if (a == null || b == null) {
        return false;
    }

    if (a.length != b.length) {
        return false;
    }

    for (int i = 0; i < a.length; i++) {
        boolean check = false;

        for (int j = 0; j < b.length; j++) {
            if (a[i] * a[i] == b[j]) {
                check = true;
                b[j] = Integer.MIN_VALUE;
                break;
            }
        }

        if (!check) {
            return false;
        }
    }

    return true;
}
  • 이번 문제는 배열 비교하는 Arrays.equals를 몰랐다. 이걸 알았으면 굳이 이중 for문을 쓰지 않았을 텐데…
  • 아쉽다.
  • 다음에 배열을 비교하는 문제가 나오면 꼭 기억하자.
public static boolean comp2(int[] a, int[] b) {
    if (a == null || b == null || a.length != b.length)
        return false;

    final int l = a.length;
    if (a.length == 0)
        return true;

    for (int i = 0; i < l; i++)
        a[i] = a[i] * a[i];

    Arrays.sort(a);
    Arrays.sort(b);

    if (Arrays.equals(a, b))
        return true;
    return false;
}