您的位置:首页 > 编程语言 > Java开发

leetcode刷题记录——349.intersection of two arrays

2016-10-13 22:13 211 查看
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

     本题是求两个数组的交叉元素,返回一个包含所有交叉元素的数组,由于题目的tags中提示binarysearch/sort/hash table,自然的想到创建一个HashSet,利用Arrays.binarySearch(),在nums2中查找nums1的所有元素,将交叉元素放入这个set中

</pre><p></p><pre>
public int[] intersection(int[] nums1, int[] nums2){
//Map<Integer,Integer> hash=new HashMap<Integer,Integer>();
Set<Integer> set = new HashSet<Integer>();
Arrays.sort(nums1);
Arrays.sort(nums2);
for(int i=0;i<nums1.length;i++){
if(Arrays.binarySearch(nums2,nums1[i])>=0){
set.add(nums1[i]);
}
}
Object[] toarray=set.toArray();
int[] result=new int[toarray.length];
for(int i=0;i<result.length;i++){
result[i]=(Integer)toarray[i];
}
return result;

}



总结:

我写的这个方法思想很简单,但是有些细节需要注意——

 1.Arrays.binarysearch
(int[] a, int key)
方法针对已排序过的数组,返回key在数组a中对应的索引值,如果a中不包含key,则返回(-(插入点)-1);经过测试,插入点就是该key在已排序后的数组a中可以插入的位置。

2.Set.toarray()方法返回的是Object类型的数组,最开始我想用

Integer[] toarray=(Integer[])set.toArray();


编译时抛出异常,后来改成现在这种方式后发现没有问题;

其实写完之后发现sort时间复杂度还是比较高,所以可以不用排序,用两个set来完成,这里就不赘述了。小白的第一篇博客,希望自己继续努力,可以离大神越来越近~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode