2014-04-01 76 views
0

我有兩個數組列表,我正在尋找一種有效的方法來計算不同值的數量。比較兩個不同的數組列表並獲得差異java

一些示例清單:

List<String> list = new ArrayList<String>(); 
    list.add("String A"); 
    list.add("String B"); 
    list.add("String C"); 

List<String> anotherlist = new ArrayList<String>(); 
    list.add("String B"); 
    list.add("String A"); 
    list.add("String D"); 

你可以做些什麼來檢查每個項目(因爲爲了不應該的問題),如果是相同或不(純概念):

for(int i=0;i<list.size();i++) 
    { 
      for(int j=0;j<anotherlist.size();j++) 
      { 
        if (item.get(i) == item.get(j)){ 
         intDifferent = intDifferent+1; 
        } else { 
         intSame = intSame+1; 
        } 
        intTotal = intTotal+1 
      } 
    } 

    //Some calculations with intdifferent en inttotal to find out how many different 
    //values we actually have between the lists, in the case of the example, it 
    //should output 1 

有沒有更有效的方法來做到這一點?或者是否有可用的樣本或文章來說明如何實現這一目標?

回答

0

你應該看看使用Set這個。

將所有項目從一個陣列放入HashSet,然後遍歷另一個陣列檢查它是否包含在Set中。

這比每次循環播放ArrayList要快得多。

+0

請告訴他,也可以通過等於比較字符串。 – Seelenvirtuose

+0

@Seelenvirtuose你當然是正確的,但使用我的建議,他根本不會做任何比較:) –

+0

我知道。散列數據結構處於最佳狀態。 :-) – Seelenvirtuose

0

下面的算法最壞情況下的複雜度爲O(n *的log(n))

// worst case O(nLog(n)) 
    Collections.sort(l1); 
    // worst case O(nLog(n)) 
    Collections.sort(l2); 

    // pointer for l1 list 
    int p = 0; 

    // pointer for l2 list 
    int q = 0; 

    int diffCounter = 0; 
    // worst case N 
    while (true) { 

     if (p == l1.size() -1) { 
      // remainig items in l2 list are diff 
      diffCounter += (l2.size() -1) - q; 
      break; 
     } 
     if (q == l2.size() -1) { 
      diffCounter += (l1.size() - 1) - p; 
     } 

     int compareResult = l1.get(p).compareTo(l2.get(q)); 
     if (compareResult > 0) { 
      p++; 
      diffCounter++; 
     } else if (compareResult < 0) { 
      q++; 
      diffCounter++; 
     } 

`

相關問題