Finding common elements in two arrays of different size

后端 未结 10 801
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 18:08

I have a problem to find common elements in two arrays and that\'s of different size.

Take , Array A1 of size n and Array A2 o

相关标签:
10条回答
  • 2020-12-14 18:30

    I solve the problem by using Set intersection. It is very elegant. Even though I did not analyze the time complexity, it is probably in reasonable range.

    public Set FindCommonElements(Integer[] first, Integer[] second)
    {
    
        Set<Integer> set1=new HashSet<Integer>(Arrays.asList(first));
        Set<Integer> set2=new HashSet<Integer>(Arrays.asList(second));
    
        // finds intersecting elements in two sets
        set1.retainAll(set2);
    
        return set1;
    
    }
    
    0 讨论(0)
  • 2020-12-14 18:31

    If you want to make it efficient I would convert the smaller array into a hashset and then iterate the larger array and check whether the current element was contained in the hashset. The hash function is efficient compared to sorting arrays. Sorting arrays is expensive.

    Here's my sample code

    import java.util.*;
    public class CountTest {     
        public static void main(String... args) {        
            Integer[] array1 = {9, 4, 6, 2, 10, 10};
            Integer[] array2 = {14, 3, 6, 9, 10, 15, 17, 9};                    
            Set hashSet = new HashSet(Arrays.asList(array1)); 
            Set commonElements = new HashSet();        
            for (int i = 0; i < array2.length; i++) {
                if (hashSet.contains(array2[i])) {
                    commonElements.add(array2[i]);
                }
            }
            System.out.println("Common elements " + commonElements);
        }    
    }
    

    Output:

    Common elements [6, 9, 10]

    0 讨论(0)
  • 2020-12-14 18:35

    In APL:

    ∪A1∩A2
    

    example:

          A1←9, 4, 6, 2, 10, 10
          A1
    9 4 6 2 10 10
    
          A2←14, 3, 6, 9, 10, 15, 17, 9
          A2
    14 3 6 9 10 15 17 9
    
          A1∩A2
    9 6 10 10
          ∪A1∩A2
    9 6 10 
    
    0 讨论(0)
  • 2020-12-14 18:35

    Looks like nested loops:

    commons = empty
    for each element a1 in A1
       for each element a2 in A2
          if a1 == a2
             commons.add(a1)
    

    Schouldn't matter at all if the arrays have the same size.

    Depending on the language and framework used, set operations might come in handy.

    0 讨论(0)
  • 2020-12-14 18:44

    Sort the arrays. Then iterate through them with two pointers, always advancing the one pointing to the smaller value. When they point to equal values, you have a common value. This will be O(n log n+m log m) where n and m are the sizes of the two lists. It's just like a merge in merge sort, but where you only produce output when the values being pointed to are equal.

    def common_elements(a, b):
      a.sort()
      b.sort()
      i, j = 0, 0
      common = []
      while i < len(a) and j < len(b):
        if a[i] == b[j]:
          common.append(a[i])
          i += 1
          j += 1
        elif a[i] < b[j]:
          i += 1
        else:
          j += 1
      return common
    
    print 'Common values:', ', '.join(map(str, common_elements([1, 2, 4, 8], [1, 4, 9])))
    

    outputs

    Common values: 1, 4
    

    If the elements aren't comparable, throw the elements from one list into a hashmap and check the elements in the second list against the hashmap.

    0 讨论(0)
  • 2020-12-14 18:50

    Throw your A2 array into a HashSet, then iterate through A1; if the current element is in the set, it's a common element. This takes O(m + n) time and O(min(m, n)) space.

    0 讨论(0)
提交回复
热议问题