LeetCode知识点总结 - 349

LeetCode 349. Intersection of Two Arrays

考点 难度
Array Easy
题目

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

Guess you like

Origin blog.csdn.net/m0_59773145/article/details/119117789
Recommended