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

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来完成,这里就不赘述了。小白的第一篇博客,希望自己继续努力,可以离大神越来越近~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值