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;
}
在局部變量中保留'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