Find common elements in three sorted arrays

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);

	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章