349. Intersection of Two Arrays

本文介绍了两种计算两个数组交集的有效方法。方法一利用了Set集合的特性来去除重复元素并找出交集;方法二通过先对两个数组进行排序,然后使用双指针技巧来寻找相同元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

方法一:

// 利用set集合的特性(集合中的数据是无序,且唯一),来解决此问题
	public int[] intersection(int[] nums1, int[] nums2) {
		Set<Integer> set = new HashSet<Integer>(); //用来存放数组nums1中无重复的数据
		Set<Integer> intersec = new HashSet<Integer>();
		// 将数组nums1中的数组存放在set集合中
		for (int i=0; i<nums1.length; i++) {
			set.add(nums1[i]);
		}
		
		// 将数组nums2中的元素在set集合中进行查找,如果找到,则说明为相交元素
		for ( int j = 0; j <nums2.length; j++) {
			if ( set.contains(nums2[j])) {
				intersec.add(nums2[j]);
			}
		}
		
		// 将intersec集合中的数据转存到数组中,并返回出去
		int[] result = new int[intersec.size()];
		int i = 0;
		for (Integer num : intersec) {
			result[i++] = num;
		}
		return result;
	}
方法二:
// 算法思想:
	/*
	 * 1:先将数组排序
	 * 2:两两比较
	 */
	public int[] intersection(int[] nums1, int[] nums2) {
		Arrays.sort(nums1);
		Arrays.sort(nums2);
		// 用于存储结果的set集合
		Set<Integer> intersect = new HashSet<Integer>();
		int i = 0; // 将i指向数组nums1
		int j = 0; // 将j指向数组nums1
		// 在数组nums1和数组nums2都有元素的情况下循环
		while ( i<nums1.length && j<nums2.length) {
			if ( nums1[i] < nums2[j] ) {
				i++;
			} else if ( nums1[i] > nums2[j]) {
				j++;
			} else {
				intersect.add(nums1[i]);
				i++;
				j++;
			}
		}
		
		int[] result = new int[intersect.size()];
		int m = 0;
		for (Integer num : intersect) {
			result[m] = num;
		}
		return result;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值