LeetCode知识点总结 - 349

LeetCode 349. Intersection of Two Arrays

考点难度
ArrayEasy
题目

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

重点
  1. HashSet
    题目要求结果里不能有重复数字,所以利用HashSet不能储存重复数据的特点保证结果没有重复。
  2. Array必须指定长度
    因为在declare array的时候必须指定长度,而这个长度自然会大于等于实际重复数字的个数,需要在判断数字是否重复的时候计数并且在最后返回结果的时候进行特殊操作。
答案

大概思路:
HashSet储存nums1里面的所有值,array储存重复值,pointer记录重复值个数。
对于nums2里面存在的值,判断是否存在于HashSet。如果存在,从HashSet中删除并加在array里面。同时pointer加一。
返回结果。

public int[] intersection(int[] nums1, int[] nums2) {
	Set<Integer> numbers = new HashSet<>();
	for (int n : nums1) { numbers.add(n); }
	int[] res = new int[numbers.size()];
	int pointer = 0;
	for (int n : nums2) {
		if (numbers.remove(n)) {
			res[cursor++] = n;
		}
	}
	return Arrays.copyOfRange(res,0,cursor);
}

*这道题也可以用two pointers方法,详情见350

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值