Geeksforgeeeks上的一道题,原文http://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/
iven three arrays sorted in non-decreasing order, print all common elements in these arrays.
Examples:
ar1[] = {1, 5, 10, 20, 40, 80}
ar2[] = {6, 7, 20, 80, 100}
ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20, 80
ar1[] = {1, 5, 5}
ar2[] = {3, 4, 5, 5, 10}
ar3[] = {5, 5, 10, 20}
Outptu: 5, 5
最直接的想法是,先把两个数组取交集,然后在和第三个取交集。因为数组已经排好序,所以时间复杂度为 O( n1 + n2+n3),并且需要额外空间。
Solution:
利用求交集的思想,我们可以用三个指针,时间复杂度依旧为O( n1 + n2+n3),但可以one loop实现,O(c) space
1) If x, y and z are same, we can simply print any of them as common element and move ahead in all three arrays.
2) Else If x < y, we can move ahead in ar1[] as x cannot be a common element
3) Else If y < z, we can move ahead in ar2[] as y cannot be a common element
4) Else (We reach here when x > y and y > z), we can simply move ahead in ar3[] as z cannot be a common element.
public static ArrayList<Integer> findCommon(int ar1[], int ar2[], int ar3[]){
int n1 = ar1.length, n2 = ar2.length, n3 = ar3.length;
ArrayList<Integer> res = new ArrayList<Integer>();
if(ar1 == null || ar2 == null || ar3 == null || n1 == 0 || n2 == 0 || n3 == 0){
return null;
}
//initialize three pointer
int i = 0, j = 0, k = 0;
// Iterate through three arrays while all arrays have elements
while(i < n1 && j < n2 && k < n3){
if(ar1[i] == ar2[j] && ar2[j] == ar3[k]){
// If x = y and y = z, common element
res.add(ar1[i]);
i++;
j++;
k++;
}else if(ar1[i] < ar2[j]){
i++;
}else if(ar2[j] < ar3[k]){
j++;
}else{
//when x > y and z < y, so z is smallest
k++;
}
}
return res;
}
/*
* A simple solution:
* (1)first find intersection of two arrays and store the intersection in a temporary array,
* (2)find the intersection of third array and temporary array.
* Time complexity of this solution is O(n1 + n2 + n3)
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int ar1[] = {1, 5, 10, 20, 40, 80};
int ar2[] = {6, 7, 20, 80, 100};
int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120};
System.out.println( "Common Elements are ");
ArrayList<Integer> res = findCommon(ar1, ar2, ar3);
System.out.println(res);
}