349. Intersection of Two Arrays双指针|二分
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了349. Intersection of Two Arrays双指针|二分相关的知识,希望对你有一定的参考价值。
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;
}
以上是关于349. Intersection of Two Arrays双指针|二分的主要内容,如果未能解决你的问题,请参考以下文章
349. Intersection of Two Arrays
349. Intersection of Two Arrays
Leetcode 349. Intersection of Two Arrays
[leetcode]349.Intersection of Two Arrays