资讯专栏INFORMATION COLUMN

[LeetCode] Intersection of Two Arrays I & II

lucas / 2403人阅读

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 map = new HashMap();
        List 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 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 record = new HashSet<>();
        Set 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 res = new ArrayList();
        Map 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 record = new HashMap<>();
        for (int num: nums1) {
            if (record.containsKey(num)) {
                record.put(num, record.get(num)+1);
            } else record.put(num, 1);
        }
        List 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;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65996.html

相关文章

  • LeetCode 350. Intersection of Two Arrays II

    摘要:描述给定两个数组,编写一个函数来计算它们的交集。示例输入输出示例输入输出说明输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。我们可以不考虑输出结果的顺序。思路对数组进行排序。如果所在的元素大,则向后走一步。 Description Given two arrays, write a function to compute their intersection. Exa...

    余学文 评论0 收藏0
  • [LintCode/LeetCode] Intersection of Two Arrays I &

    摘要:先想到的是,其实也可以,只是需要在遍历的时候,添加到数组中的数要掉,略微麻烦了一点。在里跑的时候,也要快一点。另一种类似做法的就快的多了。如果是找出所有包括重复的截距呢 Problem Given two arrays, write a function to compute their intersection. Notice Each element in the result m...

    enda 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • leetcode349. Intersection of Two Arrays

    摘要:题目要求找出两个无序数组中重合的值。先将两个数组分别排序,排序完成之后再用两个指针分别比较两个数组的值。如果两个指针指向的值相同,则向结果集中添加该元素并且同时将两个指针向前推进。答案是为其中一个数组通过建立索引的方式排序。 题目要求 Given two arrays, write a function to compute their intersection. Example: ...

    only_do 评论0 收藏0

发表评论

0条评论

lucas

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<