2012-10-16 94 views
9

我的目標是找出數組a和b的交集值並將它們存儲到一個新數組c中,因此打印輸出爲:3,10,4,8。我如何將給定的值賦給第三個數組c?查找兩個數組的交集

public static void main(String[] args) { 
     int a[] = {3, 10, 4, 2, 8}; 
     int[] b = {10, 4, 12, 3, 23, 1, 8}; 
     int[] c; 
     int i=0; 
     for(int f=0;f<a.length;f++){ 
       for(int k=0;k<b.length;k++){ 
        if(a[f]==b[k]){ 
//here should be a line that stores equal values of 2 arrays(a,b) into array c 
      } 
      } 
     } 
      for (int x=0; x<c.length; x++){ 
      System.out.println(c[i]); 
      } 
     } 
    } 
+1

如果這不是家庭作業要求嚴格陣列ickies,看'Set'接口 - 如果需要維護或維護,它稍微複雜一點,但不是很多。 – 2012-10-16 16:26:48

+0

你的代碼就在那裏,而我(ndex)從0開始並沒有被使用。 – CBredlow

+0

檢查此鏈接http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html –

回答

0

如果允許使用的ArrayList爲C,其可增長的陣列

ArrayList c = new ArrayList(); 
. 
. 
. 
. 
. 
c.add(a[f]); 

也如果允許數組進行排序,我建議你進行排序較小數組中,然後遍歷較大陣列和二分搜索在較小的陣列。

+0

我認爲你應該澄清,如果允許,這是一個很好的解決方案。對於我們所知道的,OP的項目可能會有一些不允許使用ArrayList的限制。 –

+0

謝謝。我確信這會做我需要的東西,但我還不熟悉ArrayLists。 –

0

首先,你需要爲你的數組分配空間:

int[] c = new int[SOME_SIZE]; 

難的是找出多少SOME_SIZE應該的。由於您正在計算交叉點,因此最多可以是ab中最小的尺寸。

最後,爲了分配數組中的元素,你只是做

c[idx] = a[f] 

現在你需要跟蹤下idx去。我建議從idx = 0開始,並在每次找到新元素時將其遞增,以便將其添加到c

+0

這對於初學者來說是令人困惑的。但是,謝謝:) –

+0

@AlexandrMelnik如果您感到困惑,我建議您嘗試編寫一個程序,將一個陣列複製到另一個陣列。如果在這個更簡單的程序中使用數組仍然存在問題,那麼您應該閱讀更多關於它們的信息,並返回一些具體問題以供澄清。 –

9

這應該是一個簡單的方法。

int a[] = {3, 10, 4, 2, 8}; 
int[] b = {10, 4, 12, 3, 23, 1, 8}; 
List<Integer> aList = Arrays.asList(a); 
List<Integer> bList = Arrays.asList(b); 
aList.retainAll(bList); 
System.out.println(" a intersection b "+aList); 
int[] c = aList.toArray(new int[0]); 
+0

謝謝。我確信這會做我需要的東西,但我還不熟悉ArrayLists。 –

+0

這不會編譯。首先,因爲'Arrays.asList'返回一個'List

1
public static void main(String[] args) { 
     int a[] = {3, 10, 4, 2, 8}; 
     int[] b = {10, 4, 12, 3, 23, 1, 8}; 
     int[] c = new int[(int)Math.min(a.length, b.length)]; 
     int i=0; 
     for(int f=0;f<a.length;f++){ 
       for(int k=0;k<b.length;k++){ 
        if(a[f]==b[k]){ 
        c[i] = a[f]; 
        i++; 
      } 
      } 
     } 
     for (int x=0; x<i; x++){ 
      System.out.println(c[x]); 
     } 
     } 
    } 

希望它能幫助。或者如果您有時間複雜性問題,請嘗試Java Set

0

你可以採取臨時變量的幫助(但這基本上是重新發明輪子,如果你不這樣做需要) -

int[] c = new int[0]; 
//... 
    if(a[f] == b[k]) { 
     int[] temp = c; 
     c = new int[c.length + 1]; 
     for(int i=0; i<temp.length; i++) { 
      c[i] = temp[i]; 
     } 
     c[c.length - 1] = a[f]; 
    } 
//... 
+0

只要這兩種方式都是對的,我可以更喜歡他們中的任何一種:) 謝謝 –

+0

不客氣。 :) –