2015-04-01 58 views
1

所以我最近在技术面试中得到了以下问题,我认为这很有趣。交集与扭曲的集合Java

给定两个数组: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); 

} 
} 

****编辑***** 我误称为阵列设置,当我最初提出的问题。由于数组可以有重复的元素,它们根据定义不是集合。对困惑感到抱歉。

+1

'地图hashtable' ....我的眼睛X_X – gtgaxiola 2015-04-01 14:01:58

+4

'{1,2,2,4,5}'不是一套。 – dasblinkenlight 2015-04-01 14:02:16

+0

建议使用java Set来实现你的集合A和B.根据列表 – gefei 2015-04-01 14:02:23

回答

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] 
+0

执行设置的工作量会少一些。不幸的是,这不适用于重复项。如果A是{1,2,2,3},那么b是{2,4} A-B应该是{1,2,3},只删除在b中找到的单个2。设置的操作会删除a中所有出现的2。 – 2015-04-01 14:31:01

+1

那么按照定义A = {1,2,2,3}不是一个集合。 – gtgaxiola 2015-04-01 14:35:47

+0

我的错误。我想他们只是阵列。 – 2015-04-01 15:52:04

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]