码迷,mamicode.com
首页 > 其他好文 > 详细

Common Element in Two Sorted Sets

时间:2016-01-24 06:57:54      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

There are 2 sorted sets.Find the common elements of those sets 
e.g. 
A={1,2,3,4,5,6} 
B={5,6,7,8,9} 
o/p C={5,6} 

Complexity should ne 0(n+m) where n and m is the size of the first and second set respectively 

Which data structure should be used to store the output

 

List<int> FindIntersection(int[] A, int[] B)
{
         int L = A.Length;
         int K = B.Length;

         List<int> intersectionArr = new ArrayList<int>();
         int i = L - 1;
         int j = K - 1;
         
          while ((i >= 0) && (j >=  0))
          {
                 if (A[i] > B[j])
                 {
                        i--;
                 }
                 else if (B[j] > A[i])
                 {
                         j--;
                 }
                 else
                 {
                         intersectionArr.Add(A[i]);
                          i--;
                          j--;
                        
                 }
          }
          return intersectionArr;
}

 

Common Element in Two Sorted Sets

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5154494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!