【leetcode常见面试题】349. 两个数组的交集

【主要考察点】:哈希表、双指针
在这里插入图片描述

解题方法

1. 哈希表解法

在Java中可以利用Set集合的特性帮助我们完成去重的工作。

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // 构建两个set集合,先对nums1、nums2两个数组进行去重
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for(int num : nums1){
        	set1.add(num);
        }
        for(int num : nums2){
        	set2.add(num);
        }
        // 再构建一个set集合,用于保存交集数据
        Set<Integer> set3 = new HashSet<>();
        // 因为取交集,所以任意遍历nums1或者nums2其中一个集合即可
        for(int num : set1){
        	if(set2.contains(num)){
        		set3.add(num);
        	}
        }
		
		// 最后转换成数组。
		int[] result = new int[set3.size()];
		int idx = 0;
		for(int num : set3){
			result[idx++] = num;
		}
		return result;
    }
}

2. 排序+双指针

排序+双指针组合,也是一种常用的对结果集进行遍历、比较的方式

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // 先排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);
		
		// 定义两个指针
		int idx1 = 0, idx2 = 0;
		int len1 = nums1.length, len2 = nums2.length;
		
		// 保存交集数据
		int[] nums3 = new int[len1 + len2];
		int idx3 = 0;
		while(idx1 < len1 && idx2 < len2){
			// 交集数据
			if(nums1[idx1] == nums2[idx2]){
				// 过滤掉nums3中已经存在的
				if(idx3 == 0 || nums1[idx1] != nums3[idx3-1]){
					nums3[idx3++] = nums1[idx1];
				}
				idx1++;
				idx2++;
			}else if(nums1[idx1] > nums2[idx2]){
				idx2++;
			}else{
				idx1++;
			}
		}
		return Arrays.copyOfRange(nums3, 0, idx3);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值