如何在java中从两个数组中查找不常见的值

时间:2018-06-18 08:15:18

标签: java

我可以使用if condition和==从两个数组中找到常用值 但不能找到不寻常的意思是获得独特的价值观,请帮助我 得到不常见的价值......

常用值:3我得到了预期的输出

罕见值:1 2 4 5如何获得!=条件不起作用

int a[] = {1,2,3};
int b[] = {3,4,5};

void commonValues(){
    for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
            if (a[i]==b[j]){
                System.out.println("Common values: "+a[i]);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:5)

您的代码是 O(n ^ 2),即大型阵列的性能特性不佳。

为了获得更好的性能,请使用Set而不是数组。 Set然后提供了很好的辅助方法。

以下是示例代码(有关集合运算符,请参阅Wikipedia):

public static void main(String[] args) {
    int a[] = {1,2,3};
    int b[] = {3,4,5};

    Set<Integer> setA = toSet(a);
    Set<Integer> setB = toSet(b);

    // common = A ∩ B
    Set<Integer> common = new TreeSet<>(setA); // use TreeSet for sorted result
    common.retainAll(setB); // intersection: ∩
    System.out.println("common: " + common);

    // uncommon = (A ∪ B) \ common
    Set<Integer> uncommon = new TreeSet<>(setA); // use TreeSet for sorted result
    uncommon.addAll(setB); // union: ∪
    uncommon.removeAll(common); // asymmetric difference: \
    System.out.println("uncommon: " + uncommon);
}
private static Set<Integer> toSet(int... arr) {
    Set<Integer> set = new HashSet<>(arr.length * 4 / 3 + 1);
    for (int v : arr)
        set.add(v);
    return set;
}

输出

common: [3]
uncommon: [1, 2, 4, 5]