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
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4]
说明:
幼稚的方法是根据第一个数组 nums1 迭代并检查每个值是否存在在 nums2 内。如果存在将值添加到输出。这样的方法会导致 O(nxm) 的时间复杂性,其中 n 和 m 是数组的长度。
使用set 来实现线性时间复杂度
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function(nums1, nums2) { // 使用 set 来存储结果 const result = new Set(); const set2 = new Set(nums2); for(let i = 0; i < nums1.length; i++) { // set查找的时间复杂度为 O(1) if(set2.has(nums1[i])) { result.add(nums1[i]); } } // 最后需要将set转成数组 return Array.from(result); };
LeetCode第349题:两个数组的交集题解
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目描述
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
示例 2:
说明:
解题思路
幼稚的方法是根据第一个数组 nums1 迭代并检查每个值是否存在在 nums2 内。如果存在将值添加到输出。这样的方法会导致 O(nxm) 的时间复杂性,其中 n 和 m 是数组的长度。
使用set 来实现线性时间复杂度
解法方法
复杂度分析
参考
LeetCode第349题:两个数组的交集题解
The text was updated successfully, but these errors were encountered: