Menu
CoddyTech

Intersection of Two Arrays

简单哈希python iconjava iconcpp iconc iconjs icon+10

你会得到两个整数数组,nums1 和 nums2。返回同时出现在两个数组中的所有值,并按升序排列。每个共有值在答案中只出现一次,无论它在任一数组中重复了多少次。

函数

intersection(nums1: integer-array, nums2: integer-array) → integer-array
nums1integer-array
第一个整数列表
nums2integer-array
第二个整数列表
返回值integer-array
两个列表中都出现的值,每个值只出现一次,并按升序排列

约束条件

  • 1 ≤ nums1.length, nums2.length ≤ 5000
  • -105 ≤ nums1[i], nums2[i] ≤ 105
  • 至少有一个值同时出现在两个数组中。

示例

输入
nums1 = [6, 2, 9, 2, 4]nums2 = [4, 4, 1, 6]
输出
[4, 6]
解释
4 和 6 都在两个数组中。4 在 nums2 中出现了两次,但只列出一次,而 2 和 9 从未出现在 nums2 中。
challenge icon

进阶

如果 nums1 有 10 个值,而 nums2 有一百万个值,并且已经排好序,你会选择哪种方法?二分查找能比完整遍历更快吗?

重置代码
def intersection(nums1, nums2):
    # 在这里编写代码

测试 #1

测试 #2

参数

nums1 = [6, 2, 9, 2, 4]
nums2 = [4, 4, 1, 6]

预期输出

[4, 6]