How to intersect two sorted integer arrays without duplicates?

后端 未结 6 2026
庸人自扰
庸人自扰 2020-12-30 08:02

This is an interview question that I am using as a programming exercise.

Input: Two sorted integer arrays A and B in increasing order and of differe

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 08:55

    If you are using 'Integer' (object) arrays and would like to use the java API methods, you can check the below code. Note that the below code probably has more complexity (as it uses some conversion logic from one datastructure to other) and memory consumption (because of using objects) than the primitive method, as listed above. I just tried it (shrugs):

    public class MergeCollections {
        public static void main(String[] args) {
            Integer[] intArray1 = new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            Integer[] intArray2 = new Integer[] {2, 3, 5, 7, 8, 11, 13};
    
            Set intSet1 = new TreeSet();
            intSet1.addAll(Arrays.asList(intArray1));
            intSet1.addAll(Arrays.asList(intArray2));
            System.out.println(intSet1);
        }
    }
    

    And the output:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13]
    

    Also, check this link: Algolist - Algo to merge sorted arrays

    EDIT: Changed HashSet to TreeSet

    EDIT 2: Now that the question is edited and clear, I'm adding a simple solution to find intersection :

    public class Intersection {
        public static void main(String[] args) {
            Integer[] intArray1 = new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            Integer[] intArray2 = new Integer[] {2, 3, 5, 7, 8, 11, 13};
    
            List list1 = Arrays.asList(intArray1);
            Set commonSet = new TreeSet();
            for(Integer i: intArray2) {
                if(list1.contains(i)) {
                    commonSet.add(i);
                }
            }
    
            System.out.println(commonSet);
        }
    }
    

提交回复
热议问题