Skip to content

Latest commit

 

History

History
126 lines (102 loc) · 2.31 KB

349.intersection-of-two-arrays.md

File metadata and controls

126 lines (102 loc) · 2.31 KB

题目地址

https://leetcode.com/problems/intersection-of-two-arrays/description/

题目描述

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.

思路

先遍历第一个数组,将其存到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)