2013-03-27 34 views
-2

例如:如何計算兩個數組中的等值數?

int[] a = [0,1,2,3,4,5]; 
int[] b = [3,4,5,6,7,8]; 

count = 3; 

所述陣列不必是連續號碼。 我將如何獲得這些數組之間相等的值的數量?

編輯:所以,我已經嘗試以下操作:

List<int[]> w = Arrays.asList(winning); 
List<int[]> s = Arrays.asList(F1Select);    
w.retainAll(s); 
int equalNums = w.size(); 

但我發現了以下錯誤的行的retainAll:

Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException 
    at java.util.AbstractList.remove(Unknown Source) 
    at java.util.AbstractList$Itr.remove(Unknown Source) 
    at java.util.AbstractCollection.retainAll(Unknown Source) 
+5

你嘗試過什麼?基本邏輯是跟蹤你已經訪問過的那些。 – 2013-03-27 18:31:29

+1

我推薦你先對數組進行排序,然後這很容易 – 2013-03-27 18:32:03

+0

使用嵌套循環,並且是一個數組中唯一的值,還是有重複的數據? – 2013-03-27 18:32:05

回答

3

您可以直接轉換成列表,並找到交集使用retainAll。

List<Integer> aList = Arrays.asList(a); 
List<Integer> bList = Arrays.asList(b); 
aList.retainAll(bList); 
return aList.size(); 

aList將只包含也在bList中的項目,並且aList的大小讓您知道計數。

如果您只想要唯一的值,您可以將數組轉換爲Set並執行相同的操作。

+1

我使用Eclipse,它告訴我給我們列出而不是列表。 – 2013-03-27 18:43:17

0

如果您允許在計算過程中使用額外的空間O(m + n),則可以爲每個陣列保留一個HashMap。關鍵是每個數組元素,值是它發生的次數。一旦你計算了每個數字出現的頻率,那麼你已經簡化了這個問題來比較這兩個地圖。

無論何時您在兩個地圖中都存在關鍵字,都會在兩個陣列中都有一個數字。這些值可以讓您決定兩個數組中存在多少次該數字。

1

Try this :

Integer[] a = new Integer[]{0, 1, 2, 3, 4, 5}; 
Integer[] b = new Integer[]{3, 4, 5, 6, 7, 8}; 

    List<Integer> list1 = Arrays.asList(a); 
    Set<Integer> commonSet = new TreeSet<Integer>(); 
    for (Integer i : b) { 
     if (list1.contains(i)) { 
      commonSet.add(i); 
      } 
     } 

     System.out.println(commonSet.size());