与扭曲Java的集合的交集

时间:2015-04-01 13:59:34

标签: java hashmap runtime

所以我最近在技术面试中得到了以下问题,我认为这很有趣。

给定两个数组:A = {1,2,2,4,5}和B = {1,2,6,}写代码执行以下两个操作:AB {2,4,5}和BA {6}。意思是,您在另一个数组中找到一个公共元素并将其从原始数组中删除。同样,如果B是{1,2},那么B-A就是{},因为A包含B的所有元素,而B没有唯一的元素。

我用以下方式解决了这个问题,我希望看看是否有人对如何使其变得更好有任何建议。

public static void main(String args[]) {
Map hashtable = new HashMap();

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

ArrayList ba = new ArrayList();
ArrayList ab = new ArrayList(); 
int[] occurances = new int[a.length];
//int occurances = 0;
for (int i = 0; i < a.length; i++) {
    occurances[a[i]]++;
    hashtable.put(a[i], occurances[a[i]]);

}
//System.out.println(Arrays.toString(occurances));
System.out.println(hashtable);
//find BA
for (int i = 0; i < b.length; i++) {
    if(hashtable.containsKey(b[i])) {
        occurances[b[i]]--;
        hashtable.put(b[i], occurances[b[i]]);
    } else ba.add(b[i]);


}
for(int i = 0; i <a.length; i++) {
    if(hashtable.containsKey(a[i]) && occurances[a[i]] != 0) {
        ab.add(a[i]);
        occurances[a[i]]--;
        hashtable.put(a[i], occurances[a[i]]);

    }

}

System.out.println("AB = " + ab);
System.out.println("BA =" + ba);

 } 
 }

**** ***** EDIT 当我最初提出问题时,我错误地调用了数组。由于数组可以包含重复元素,因此根据定义它们不是集合。对困惑感到抱歉。

2 个答案:

答案 0 :(得分:2)

您可以使用具有联合和交叉功能的Set

Integer a[] = {1, 2, 2, 4, 5};
Integer b[] = {1, 2, 6};

public void test() {
    // Grow the two sets from the arrays.
    Set<Integer> sa = Arrays.stream(a)
            .collect(Collectors.toCollection(TreeSet::new));
    Set<Integer> sb = Arrays.stream(b)
            .collect(Collectors.toCollection(TreeSet::new));
    // Make a new one so I don't damage sa or sb.
    Set<Integer> sc = new HashSet<>(sa);
    sc.removeAll(sb);
    System.out.println(sa + " - " + sb + " = " + sc);
    Set<Integer> sd = new HashSet<>(sb);
    sd.removeAll(sa);
    System.out.println(sb + " - " + sa + " = " + sd);
}

打印

[1, 2, 4, 5] - [1, 2, 6] = [4, 5]
[1, 2, 6] - [1, 2, 4, 5] = [6]

答案 1 :(得分:1)

只需使用标准Set操作

即可完成
Set<Integer> a; //assume initialized with {1,2,4,5}
Set<Integer> b; //assume initialized with {1,2,6}

a.removeAll(b);
System.out.println(a);

应该给:

[4, 5]

如果您这样做:

b.removeAll(a);
System.out.println(b);

然后你会得到

[6]
相关问题