How to compare two arrays of integers order-insensitively

前端 未结 8 1265
梦谈多话
梦谈多话 2021-01-19 13:23

I want Java code that can compare in this way (for example):

<1 2 3 4>  = <3 1 2 4>
<1 2 3 4> != <3 4 1 1>

I can\'t

8条回答
  •  耶瑟儿~
    2021-01-19 13:54

    Since this is homework, I'm going to guess that a simple quadratic solution (which your original attempt is), is fine. In that case, you can do something like this:

    int count(int[] nums, int x) {
        int count = 0;
        for (int num : nums) {
            if (num == x) count++;
        }
        return count;
    }   
    boolean equals(int[] arr1, int[] arr2) {
        if (arr1.length != arr2.length) return false;
        for (int x : arr1) {
            if (count(arr1, x) != count(arr2, x)) return false;
        }
        return true;
    }
    

    This sacrifices speed for clarity: it's obviously correct!!

    Tips

    • Use for-each whenever applicable; it always read to better readability
    • Helper functions improve both readability and reusability!

提交回复
热议问题