2013-02-24 72 views
0

我寫了一個方法來取兩個排序數組並返回一個包含所有常用值的數組,忽略重複項。它有很多重複。我不確定這只是問題的本質,或者我的代碼需要大量改進。這裏是我的代碼:找到兩個排序數組的交集 - 如何簡化我的代碼

static ArrayList<Integer> findCommon(int[] a, int[] b) { 
    ArrayList<Integer> res = new ArrayList<Integer>(); 
    int ai = 0, bi = 0; 
    int sizeA = a.length, sizeB = b.length; 
    while(ai < sizeA && bi < sizeB) { 
     // Ignore duplicates 
     if(ai != 0 && a[ai] == a[ai-1]) { 
     ai++; 
     continue; 
     } 
     if(bi != 0 && b[bi] == b[bi-1]) { 
     bi++; 
     continue; 
     } 

     if(a[ai] < b[bi]) { 
     ai++; 
     } else if(a[ai] > b[bi]) { 
     bi++; 
     } else if(a[ai] == b[bi]) { 
     res.add(a[ai]); 
     ai++; 
     bi++; 
     } 
    } 

    // Need to keep going in case the last element of one array is contained 
    // in the other at a later point 
    while(ai < sizeA) { 
     // Ignore duplicates 
     if(ai != 0 && a[ai-1] == a[ai]) { 
     ai++; 
     continue; 
     } 
     if(b[bi-1] < a[ai]) { 
     break; 
     } else if(b[bi-1] > a[ai]) { 
     ai++; 
     } else if(b[bi-1] == a[ai]) { 
     res.add(a[ai]); 
     ai++; 
     } 
    } 
    while(bi < sizeB) { 
     // Ignore duplicates 
     if(bi != 0 && b[bi-1] == b[bi]) { 
     bi++; 
     continue; 
     } 
     if(a[ai-1] < b[bi]) { 
     break; 
     } else if(a[ai-1] > b[bi]) { 
     bi++; 
     } else if(a[ai-1] == b[bi]) { 
     res.add(b[bi]); 
     bi++; 
     } 
    } 
    return res; 
    } 
+0

在局部變量中保留'a [ai]'和'b [bi]',用'a [0]'和'b [0]'初始化並隨時更新。 (提示:[角落案例](http://stackoverflow.com/questions/1036666/what-is-the-usage-of-array-of-zero-length)?)那麼你應該能夠失去最後兩個'while'循環。 – krlmlr 2013-02-24 23:57:26

回答

1

ArrayList有一個Contains()方法。那麼怎麼樣;

ArrayList<Integer> intersect = new ArrayList<Integer>(); 

if (a.length > b.length) 
{ 
    for (int i = 0; i < a.length; i++) 
    { 
     if (b.Contains(a[i]) && !intersect.Contains(a[i])) 
     { 
      intersect.Add(a[i]); 
     } 
    } 
} 
else 
{ 
    // a for loop that is opposite of the above. 
} 

通過對最長陣列執行for循環,確保檢查所有條目。 intersect.Contains(a[i])表示它將忽略重複項。