問題: 給你兩個排序的數組,求兩個數組的交集。
比如: A = 1 3 4 5 7, B = 2 3 5 8 9, 那么交集就是 3 5,n是a數組大小,m是b數組大小。
思路:
(1)從b數組遍歷取值,然后把值與a數組的每一個值進行比較,如果有相等的,就保存下來,直到ab全部遍歷完,這樣時間復雜度就是O(nm)。
(2)把上面的改進一下,我們在把b里面的值與a比較時,我們采取二分搜索的方式(因為數組都是有序的),這樣的話時間復雜度就會變為O(mlogn),如果a數組更小的話,我們會取a數組的值去和b比較,這樣的話就是O(nlogm)。
(3)要做到O(n+m),上面兩種顯然是不可以的,這時我們采取雙指針的方式,因為數組A B均排過序,所以,我們可以用兩個“指針”分別指向兩個數組的頭部,如果其中一個比另一個小,移動小的那個數組的指針;如果相等,那么那個值是在交集里,保存該值,這時,同時移動兩個數組的指針。一直這樣操作下去,直到有一個指針已經超過數組范圍。
代碼如下:
public List<Integer> intersection(int[] A, int[] B) { if (A == null || B == null || A.length == 0 || B.length == 0) return null; ArrayList<Integer> list = new ArrayList<Integer>(); int pointerA = 0; int pointerB = 0; while (pointerA != A.length && pointerB != B.length) { if (A[pointerA] > B[pointerB]) { pointerB++; } else if (A[pointerA] < B[pointerB]) { pointerA++; } else { list.add(A[pointerA]); pointerA++; pointerB++; } } return list; }
並集代碼如下:
public List<Integer> union(int[] A, int[] B) { if (A == null || B == null || A.length == 0 || B.length == 0) return null; ArrayList<Integer> list = new ArrayList<Integer>(); int pointerA = 0; int pointerB = 0; while (pointerA < A.length && pointerB < B.length) { if (A[pointerA] > B[pointerB]) { list.add(B[pointerB]); pointerB++; } else if (A[pointerA] < B[pointerB]) { list.add(A[pointerA]); pointerA++; } else { list.add(A[pointerA]); pointerA++; pointerB++; } } // 退出來之后,把剩余的繼續添加 while (pointerB <= B.length - 1) { list.add(B[pointerB]); pointerB++; } while (pointerA <= A.length - 1) { list.add(A[pointerA]); pointerA++; } return list; }