[LeetCode] Intersection of Two Arrays I & II

本文探讨了两个数组的交集问题,提供了多种解决方案,包括使用哈希表、排序及双指针技巧等方法,并讨论了不同场景下的最优解。

Intersection of Two Arrays I

Problem

Given two arrays, write a function to compute their intersection.

Example

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note

Each element in the result must be unique.
The result can be in any order.

我觉得intersection是最没有意义的题目,不要求连续,也不是sorted,无趣。

Solution

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap();
        List<Integer> res = new ArrayList();
        for (int i = 0; i < nums1.length; i++) {
            if (!map.containsKey(nums1[i])) map.put(nums1[i], 1);
            else map.put(nums1[i], map.get(nums1[i])+1);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (map.containsKey(nums2[i])) {
                res.add(nums2[i]);
                map.remove(nums2[i]);
            }
        }
        int[] ans = new int[res.size()];
        for (int i = 0; i < ans.length; i++) ans[i] = res.get(i);
        return ans;
    }
}

Updated 2018-8

sort two arrays, O(nlogn)
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        Set<Integer> set = new HashSet<>();
        int i = 0, j = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] < nums2[j]) i++;
            else if (nums1[i] > nums2[j]) j++;
            else {
                set.add(nums1[i]);
                i++;
                j++;
            }
        }
        int[] res = new int[set.size()];
        i = 0;
        for (Integer num: set) {
            res[i++] = num;
        }
        return res;
    }
}
two hashsets, O(n)
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> record = new HashSet<>();
        Set<Integer> intersect = new HashSet<>();
        for (int num: nums1) {
            record.add(num);
        }
        for (int num: nums2) {
            if (record.contains(num)) intersect.add(num);
        }
        int[] res = new int[intersect.size()];
        int i = 0;
        for (Integer num: intersect) {
            res[i++] = num;
        }
        return res;
    }
}

Intersection of Two Arrays II

Problem

Given two arrays, write a function to compute their intersection.

Example

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note

Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.

Follow up

What if the given array is already sorted? How would you optimize your algorithm?

What if nums1's size is small compared to num2's size? Which algorithm is better?

What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.
  
If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read 2 elements from each array at a time in memory, record intersections.

Solution

1. 8ms

import java.util.List;
import java.util.Arrays;

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> res = new ArrayList();
        Map<Integer, Integer> map = new HashMap();
        //Using HashMap to store values in nums1[]
        for (int i = 0; i < nums1.length; i++) {
            if (!map.containsKey(nums1[i])) map.put(nums1[i], 1);
            else map.put(nums1[i], map.get(nums1[i])+1);
        }
        //Modify the map with the amount of equal keys in nums2
        for (int i = 0; i < nums2.length; i++) {
            //Make sure the value of nums2[i] in map is larger than 0
            if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) {
                res.add(nums2[i]);
                map.put(nums2[i], map.get(nums2[i])-1);
            }
        }
        //Transform ArrayList() to int[]
        int[] ans = res.stream().mapToInt(Integer::intValue).toArray();
        return ans;
    }
}

2. 4ms

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int k = 0, l1 = nums1.length, l2 = nums2.length;
        int[] result = new int[l1];
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        //After sorted, just so easy
        for (int i = 0, j = 0; i < l1 && j < l2;)
            if (nums1[i] < nums2[j]) i++;
            else if (nums1[i] == nums2[j++]) result[k++] = nums1[i++];
        return Arrays.copyOf(result, k);
    }
}

Update 2018-8

One HashMap, one list convert to array, O(m+n)
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> record = new HashMap<>();
        for (int num: nums1) {
            if (record.containsKey(num)) {
                record.put(num, record.get(num)+1);
            } else record.put(num, 1);
        }
        List<Integer> res = new ArrayList<>();
        for (int num: nums2) {
            if (record.containsKey(num) && record.get(num) > 0) {
                record.put(num, record.get(num)-1);
                res.add(num);
            }
        }
        int[] intersect = new int[res.size()];
        int i = 0;
        for (int num: res) {
            intersect[i++] = num;
        }
        return intersect;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值