[LeetCode] Intersection of Two Arrays

简介: 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

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.

解题思路

首先用map存储数组1里出现的元素,然后检查这些元素是否也在数组2中存在,如果存在则将该元素添加到返回的数组中。

实现代码

// Runtime: 8 ms
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums1) {
            map.put(num, 1);
        }

        int len = 0;
        for (int num : nums2) {
            if (map.containsKey(num) && map.get(num) == 1) {
                map.put(num, 2);
                ++len;
            }
        }

        int[] nums = new int[len];
        int i = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 2) {
                nums[i++] = entry.getKey();
            }
        }
        return nums;
    }
}
目录
相关文章
|
11月前
|
存储 缓存 算法
LeetCode刷题---Two Sum(一)
LeetCode刷题---Two Sum(一)
|
9月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
22 0
|
11月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers
|
存储 算法 安全
LeetCode - #1 Two Sum
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #1 Two Sum
LeetCode 350. Intersection of Two Arrays II
给定两个数组,编写一个函数来计算它们的交集。
61 0
LeetCode 350. Intersection of Two Arrays II
|
Python
LeetCode 349. Intersection of Two Arrays
给定两个数组,编写一个函数来计算它们的交集。
59 0
LeetCode 349. Intersection of Two Arrays
LeetCode 160. Intersection of Two Linked Lists
编写一个程序,找到两个单链表相交的起始节点。
55 0
LeetCode 160. Intersection of Two Linked Lists
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
74 0
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists