2015-04-01 84 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]