Finding common elements in two arrays of different size

后端 未结 10 892
隐瞒了意图╮
隐瞒了意图╮ 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: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]

提交回复
热议问题