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
classSolution(object):
def intersection(self, nums1, nums2):
return list(set( nums1 )& set(nums2))
版本1:Java O(m*n) 循环检查
publicclassSolution{
publicint[] intersection(int[] nums1,int[] nums2){
Set<Integer> set =newHashSet<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 =newint[obj.length];
for(int i=0;i<obj.length;i++)
rs[i]=(int)obj[i];
return rs;
}
}
版本2:Java O(m+n) 借助哈希表+Set,或者双Set
publicint[] intersection(int[] nums1,int[] nums2){
Map<Integer,Boolean> map =newHashtable<Integer,Boolean>();
Set<Integer> set =newTreeSet<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 =newint[set.size()];
for(Integer num : set )
rs[i++]= num;
return rs;
}
时间: 2024-10-12 13:26:26