2017/3/23 15:41:47
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.
作弊版:Python
class Solution(object): def intersection(self, nums1, nums2): return list(set( nums1 ) & set(nums2))
版本1:Java O(m*n) 循环检查
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<Integer>(); for ( int i=0;i<nums1.length;i++ ) for ( int j=0;j<nums2.length;j++ ) if ( nums1[i] == nums2[j] ){ set.add(nums1[i]); break; } Object[] obj = set.toArray(); int[] rs = new int[obj.length]; for ( int i=0;i<obj.length;i++ ) rs[i] = (int)obj[i]; return rs; } }
版本2:Java O(m+n) 借助哈希表+Set,或者双Set
public int[] intersection(int[] nums1, int[] nums2) { Map<Integer,Boolean> map = new Hashtable<Integer,Boolean>(); Set<Integer> set = new TreeSet<Integer>(); for ( int i=0;i<nums1.length;i++ ) map.put( nums1[i] , true ); for ( int j=0;j<nums2.length;j++ ){ if (map.get(nums2[j]) == null ) continue; set.add(nums2[j]); } int i = 0; int[] rs = new int[set.size()]; for ( Integer num : set ) rs[i++] = num; return rs; }