其他分享
首页 > 其他分享> > leetcode 349 两个数组的交集

leetcode 349 两个数组的交集

作者:互联网

// 方法1
public static int[] intersection(int[] nums1, int[] nums2) {
    if (nums1 == null || nums1.length == 0
        || nums2 == null || nums2.length == 0) {
        return new int[]{};
    }

    List<Integer> integerNum1 = new ArrayList<>();
    Map<Integer, Integer> integers = new HashMap<>();
    for (int num : nums1) {
        if (!integerNum1.contains(num))
            integerNum1.add(num);
    }
    for (int num : nums2) {
        if (integerNum1.contains(num)) {
            integers.put(num, 1);
        }
    }
    int[] res = new int[integers.size()];
    int index = 0;
    for (Map.Entry entry : integers.entrySet()) {
        res[index++] = (int)entry.getKey();
    }
    return res;
 }

// 方法2
public static int[] intersection(int[] nums1, int[] nums2) {
    if (nums1 == null || nums1.length == 0
        || nums2 == null || nums2.length == 0) {
        return new int[]{};
    }

    Set<Integer> integerSet = new HashSet<>();
    for (int num : nums1) {
        integerSet.add(num);
    }
    int[] res = new int[nums2.length];
    int index = 0;
    for (int num : nums2) {
        if (integerSet.contains(num)) {
            res[index++] = num;
            integerSet.remove(num);
        }
    }
    return Arrays.copyOf(res, index);
}
// 测试用例
public static void main(String[] args) {
    int[] nums1 = new int[]{1, 2, 2, 1}, nums2 = new int[]{2, 2};
    int[] ans = intersection(nums1, nums2);
    System.out.println("Intersection demo01 result:");
    for (int res : ans) {
        System.out.print(res + " ");
    }
    System.out.println();
    nums1 = new int[]{4, 9, 5};
    nums2 = new int[]{9, 4, 9, 8, 4};
    ans = intersection(nums1, nums2);
    System.out.println("Intersection demo02 result:");
    for (int res : ans) {
        System.out.print(res + " ");
    }
    System.out.println();
}

leetcode 350: 两个数组的交集II
https://www.cnblogs.com/fyusac/p/13292985.html

标签:交集,res,nums1,349,int,num,new,leetcode,nums2
来源: https://www.cnblogs.com/fyusac/p/13913356.html