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 =
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中
总结:
我写的这个方法思想很简单,但是有些细节需要注意——
1.Arrays.binarysearch
2.Set.toarray()方法返回的是Object类型的数组,最开始我想用
编译时抛出异常,后来改成现在这种方式后发现没有问题;
其实写完之后发现sort时间复杂度还是比较高,所以可以不用排序,用两个set来完成,这里就不赘述了。小白的第一篇博客,希望自己继续努力,可以离大神越来越近~~~
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来完成,这里就不赘述了。小白的第一篇博客,希望自己继续努力,可以离大神越来越近~~~
相关文章推荐
- leetCode刷题记录-4. Median of Two Sorted Arrays
- leetcode 记录 349. Intersection of Two Arrays
- 个人记录-LeetCode 4.Median of Two Sorted Arrays
- leetcode -- Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- LeetCode: Median of Two Sorted Arrays
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode —— Median of Two Sorted Arrays
- LeetCode 笔记系列一 Median of Two Sorted Arrays
- [LeetCode题解004]Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays 解题报告
- leetcode--Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- [leetcode]Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- 【LeetCode with Python】 Median of Two Sorted Arrays
- leetCode_Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays