搜了好多文章,發現代碼是錯的,沒有達到去重的目的,而且還有人點贊,你們看代碼難道不自己測一下看對不對嗎?下面是我寫的代碼,代碼看起來長,可能確實有點冗餘,但是容易理解,如果有錯或者可以優化,麻煩你指出來,可以共同學習,謝謝。
題目要求:數組A,B有序,要求合併A,B,並且去除重複元素。
下面代碼實現的複雜度,設A和B的數組長度爲M和N那麼時間複雜度爲O(M+N),如果中用數組實現,空間複雜度也爲O(M+N)
public class Solution {
public static void main(String[] args) {
int[] A = {1,2,3,4,5};
int[] B = {1,2,2,3,4,5,5,6,7,7};
int[] result = Solution.multiply(A, B);
System.out.println(Arrays.toString(result));
}
public static int[] multiply(int[] A,int[] B) {
if (A == null && B == null || A.length < 1 && B.length < 1) {
return null;
}
// 創建輔助集合,其實數組創建新的數組也行,new int[A.length+B.length]
List<Integer> list = new ArrayList<>();
int index = 0, p1 = 0, p2 = 0;
// 先將A或者B中的首個元素添加到list
// 這裏其實得判斷是否爲null。
list.add(A[p1++]);
// 當沒有遍歷完A和B中任意一個數組時執行
while ( p1 < A.length && p2 < B.length ) {
// 拿到當前指針的最小值
int tmp = A[p1] < B[p2] ? A[p1++] : B[p2++];
// 判斷list中是否已經添加了此元素
if (tmp > list.get(index)) {
list.add(tmp);
// 每次添加元素後指針後移
index++;
}
}
// 當B中元素添加完,只剩A中元素時
while ( p1 < A.length ) {
int tmp = A[p1++];
if (tmp > list.get(index)) {
list.add(tmp);
index++;
}
}
// 當A中元素添加完,只剩B中元素時
while ( p2 < B.length ) {
int tmp = B[p2++];
if (tmp > list.get(index)) {
list.add(tmp);
index++;
}
}
// 將list中元素重新移回到數組,如果剛開始創建的是數組,那麼就不用這一步了
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}