We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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. 两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2] 输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序。
The text was updated successfully, but these errors were encountered:
注意: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); };
Sorry, something went wrong.
哈希表
/** * @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; };
No branches or pull requests
349. 两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
示例 2:
说明:
The text was updated successfully, but these errors were encountered: