2015-12-16 35 views
0

例如,以下問題狀態中之前發生:如何檢查是否一個元素陣列

收件採用兩個陣列整數作爲參數並打印他們的所有公共元素的方法。

我嘗試:現在

public static void commonElements(int[] A, int[] B) 
{ 
    for(int i = 0; i < A.length; i++) 
     for(int j = 0; j < B.length; j++) 
      if(A[i] == B[j]) 
       System.out.print(A[i] + " "); 
} 

,問題是,只有當只發生一次每個數組中的元素此代碼的工作。但是例如,如果在數組A中有兩個4,而在數組B中有四個4,則輸出將是八個4,這是錯誤的!

那麼,如何檢查數組中的某個元素是否已經發生,以便代碼不會考慮它。

+0

如果它是'發現'然後'休息' –

+0

您需要的代碼可以在[雅可布效應的答案在這個問題上堆棧溢出]中找到(http://stackoverflow.com/questions/4529819/finding-common -elements-在兩陣列-的-不同大小)。 –

回答

0
public static void commonElements(int[]A, int []B){ 

    int count = 0; 
    for(int i = 0; i < A.length; i++) 
     for(int j = 0; j < B.length; j++) 
      if(A[i] == B[j]){ 
       count++; 
       break; 
      }  
    System.out.println(count); 
} 

試試看。通過添加中斷,你可以將其強制退出循環。

0

您可以存儲您在一組中找到的內容。一套不允許重複。

public static void commonElements(int[] a, int[] b) 
{ 
    Set<Integer> duplicates = new LinkedHashSet<Integer> duplicates; 
    for(int i = 0; i < a.length; i++){ 
     for(int j = 0; j < b.length; j++){ 
      if(a[i] == b[j]){ 
       duplicates.add(a[i]); 
      } 
     } 
    } 
    System.out.println(String.join(" ", duplicates)); 
} 

注意:按照慣例,變量名在Java中應該是小寫。

相關問題