2020-11-02

11.02每日一题

349. 两个数组的交集

要计算交集,就要遍历数据中的所有数,这时候想到昨天的每日一题,可以利用hash表保存数据,这样找到每一个数的时间都是O(1),同时从例子中可以看到重复的数只统计一次,可以想到利用HashSet来作为这次存储数据的结构,考虑完要使用的数组结构之后,剩下的就简单了,只需要遍历较小的那个,找到相同的数字取出来就可以了,下面附上代码:

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> nums1Set = new HashSet<>();
        Set<Integer> nums2Set = new HashSet<>();
        for(int num : nums1){
        	nums1Set.add(num);
        }
        for(int num : nums2){
        	nums2Set.add(num);
        }
        return func(nums1Set, nums2Set);
    }
    int[] func(Set<Integer> nums1Set, Set<Integer> nums2Set){
    	//判断哪个较小,遍历较小的那个
    	if(nums1Set.size() > nums2Set.size()){
    		return func(nums2Set, nums1Set);
    	}
    	Set<Integer> tmp = new HashSet<>();
    	for(int num : nums1Set){
    		if(nums2Set.contains(num)){
    			tmp.add(num);
    		}
    	}
    	int[] res = new int[tmp.size()];
    	int i = 0;
    	for(int num : tmp){
    		res[i] = num;
    		i++;
    	}
    	return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值