349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example 1:
Example 2:
Note:
Each element in the result must be unique.
The result can be in any order.
解题要点:
分别将两条char数组存入HashSet里,以便于后面的比较。根据判断两个set的长短,由短的那条作为遍历标准,并在里面判断是否有相同数,把数加入一条新数组里,最后返回新数组的值。
Complexity Analysis
Time complexity O(n + m), where
n
andm
are arrays' lengths. O(n)time is used to convertnums1
into set, O(m) time is used to convertnums2
, andcontains/in
operations are O(1) in the average case.Space complexity : O(m+n) in the worst case when all elements in the arrays are different.
Last updated
Was this helpful?