Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✅349. 两个数组的交集 #46

Open
bazinga-web opened this issue Jul 1, 2020 · 2 comments
Open

✅349. 两个数组的交集 #46

bazinga-web opened this issue Jul 1, 2020 · 2 comments

Comments

@bazinga-web
Copy link

349. 两个数组的交集

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

 

示例 1:

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

示例 2:

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

说明:

输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序。

@bazinga-web
Copy link
Author

注意:array.prototype.includes方法复杂度为O(n),可使用Map Set .has()方法代替,复杂度为O(1)

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function (nums1, nums2) {
    let result = new Set();
    let sort = new Set(nums2);
    for (num of nums1) {
        if (sort.has(num)) {
            result.add(num);
        }
    }
    return Array.from(result);
};

@Ray-56
Copy link
Owner

Ray-56 commented Jul 2, 2020

哈希表

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function(nums1, nums2) {
	// 哈希表
	const ret = [];
	const set = new Set(nums1);
	for (let n of nums2) {
		if (set.has(n) && !ret.includes(n)) {
			ret.push(n);
		}
	}
	return ret;
};

@Ray-56 Ray-56 changed the title 349. 两个数组的交集 ✅349. 两个数组的交集 Jul 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants