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

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值