349. 两个数组的交集

题目描述

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入: nums1 = [1,2,2,1], nums2 = [2,2]	
输出: [2]

示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]	
输出: [9,4]

说明:

  • 输出结果中的每个元素一定是唯一的。

  • 我们可以不考虑输出结果的顺序。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/intersection-of-two-arrays 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

先遍历第一个数组,将其存到hashtable中, 然后遍历第二个数组,如果在hashtable中存在就push到return,然后清空hashtable即可。

关键点解析

代码

  • 语言支持:JS, Python

Javascript Code:

/*	
 * @lc app=leetcode id=349 lang=javascript	
 *	
 * [349] Intersection of Two Arrays	
 *	
 * https://leetcode.com/problems/intersection-of-two-arrays/description/	
 *	
 * algorithms	
 * Easy (53.11%)	
 * Total Accepted:    203.6K	
 * Total Submissions: 380.9K	
 * Testcase Example:  '[1,2,2,1]\n[2,2]'	
 *	
 * Given two arrays, write a function to compute their intersection.	
 *	
 * Example 1:	
 *	
 *	
 * Input: nums1 = [1,2,2,1], nums2 = [2,2]	
 * Output: [2]	
 *	
 *	
 *	
 * Example 2:	
 *	
 *	
 * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]	
 * Output: [9,4]	
 *	
 *	
 * Note:	
 *	
 *	
 * Each element in the result must be unique.	
 * The result can be in any order.	
 *	
 *	
 *	
 *	
 */	
/**	
 * @param {number[]} nums1	
 * @param {number[]} nums2	
 * @return {number[]}	
 */	
var intersection = function(nums1, nums2) {	
    const visited = {};	
    const ret = [];	
    for(let i = 0; i < nums1.length; i++) {	
        const num = nums1[i];	
        visited[num] = num;	
    }	
    for(let i = 0; i < nums2.length; i++) {	
        const num = nums2[i];	
        if (visited[num] !== undefined) {	
            ret.push(num);	
            visited[num] = undefined;	
        }	
    }	
    return ret;	
};

Python Code:

class Solution:	
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:	
        visited, result = {}, []	
        for num in nums1:	
            visited[num] = num	
        for num in nums2:	
            if num in visited:	
                result.append(num)	
                visited.pop(num)	
        return result	
    # 另一种解法:利用 Python 中的集合进行计算	
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:	
        return set(nums1) & set(nums2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值