如何检查一个数组是否具有另一个数组的平方元素(无论顺序如何)?

a = [121, 144, 19, 161, 19, 144, 19, 11]

b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] 返回 true,因为 b[] 具有元素的平方值在 a[] 中,无论顺序如何。


这是我尝试过的...


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

        int x = 0;

        if (a.equals(b)) {

            for (int i : a) {

                for (int j : b) {

                    if (a[i] == b[j] * b[j]) {

                        x++;

                    } else {

                        x--;

                    }

                }

            }

        } else {

            return false;

        }

        if (x == a.length) {

            return true;

        } else {

            return false;

        }

    }


尚方宝剑之说
浏览 123回答 6
6回答

幕布斯7119047

这很简单:static boolean comp(int a[], int b[]) {    for (int i : a) {        if (!Arrays.asList(b).contains(i*i)) {            return false;        }    }    return true;}简而言之,你遍历 a 和 b 的每个值,看看 a 的平方值是否是 b。当你发现不匹配时,你会自动返回 false。否则,返回 true。

狐的传说

public static Boolean compare(int[] a, int[] b) {&nbsp; Arrays.sort(a);&nbsp; Arrays.sort(b);&nbsp; for (int i = 0; i < a.length; i++) {&nbsp; &nbsp; if (a[i] * a[i] != b[i]) {&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; }&nbsp; return true;}

holdtom

static boolean comp(int a[], int b[]) {&nbsp; &nbsp; for (int i : a) {&nbsp; &nbsp; &nbsp; &nbsp; if (!Arrays.asList(b).contains(i*i)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true;}

慕斯王

List有一个containsAll,我会用它;使用 Java 8+ 和流可能看起来像static boolean comp(int a[], int b[]) {    return Arrays.stream(b).distinct().boxed().collect(Collectors.toList())            .containsAll(Arrays.stream(a).map(x -> x * x).boxed()            .collect(Collectors.toList()));}

繁花不似锦

bool Same(int[] arr1, int[] arr2){&nbsp; &nbsp; for (int i = 0; i < arr1.Length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var correctIndex = Array.IndexOf(arr2, (int)Math.Pow(arr1[i], 2));&nbsp; &nbsp; &nbsp; &nbsp; if (correctIndex == -1)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; arr2.Take(correctIndex);&nbsp; &nbsp; }&nbsp; &nbsp; return true;}in c#

婷婷同学_

public static Boolean compare(int[] a, int[] b) {&nbsp; Arrays.sort(a);&nbsp; Arrays.sort(b);&nbsp; for (int i = 0; i < a.length; i++) {&nbsp; &nbsp; if (a[i] * a[i] != b[i]) {&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; }&nbsp; return true;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java