LeetCode349-两个数组的交集/

交集,一开始就想到了Set,因为他里面的数字是没有重复的。

1、把数组1放到set1里面,这样set1里面全是独立的、不重复的数字。

2、把数组2的数字和set1的比较,如果存在,就放到set2里面去,这是为了对结果进行去重。

3、最后set2的元素,就是解。

set.contains 是 链表+红黑树的 所以查找是logn

 public int[] intersection(int[] nums1, int[] nums2) {

        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();

        for(int i=0;i<nums1.length;i++){
            set1.add(nums1[i]);
        }

        //这样是为了去重
        for(int i=0;i<nums2.length;i++){
            if(set1.contains(nums2[i])){
                set2.add(nums2[i]);
            }
        }

        //set2里面就是结果
        int [] result = new int[set2.size()];

        Iterator<Integer> iterator = set2.iterator();

        int count = 0;

        while (iterator.hasNext()){
            result[count++]=iterator.next();
        }

        return result;
    }
原文地址:https://www.cnblogs.com/weizhibin1996/p/9656262.html