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.
解法1:Sort + Two pointers O(NlogN) Time + O(1) Space
先考虑将两个数组排序,然后只需要维护两个指针,对于一样的数值就放入返回数组中。同时要考虑去重的情况。这点上九章的答案做的比我更简洁。
C++
Java
解法2: HashTable O(N) Time + O(N) Space
先扫描第一个数组,建立hashtable,然后扫描第二个数组,同时维持一个结果的hashtable用来去重。
C++
用到了unordered_map’s iterate method.
|
|
Java