Question
Given two arrays, write a function to compute their intersection.
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note: Each element in the result must be unique. The result can be in any order.
Explanation
有三种方法可以实现:
- 用一个HashMap存起来。Time: O(nlogn) Space: O(n)
- 两个数组都排序,然后用两个指针遍历。Time: O(nlogn) Space:O(1)
- 排序其中的一个数组,然后用binary search进行搜索。Time: O(nlogn) Space:O(1)
Code
最后一种方法的代码: