题目来源:https://leetcode-cn.com/problems/intersection-of-two-arrays/
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
#######################################################
这道题一开始我没有想到用集合,感觉非常的麻烦,假如不用集合,用数组保存结果,那数组长度用多长?怎么得到最终要返回的结果数组(要删除哪些数组元素),导致我没有写出来,看了答案用了集合就容易多了!比如,需要去重,就想到可以用set。
两种方法的代码如下,第二种使用了集合的retainAll方法。
第一种:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length==0||nums2.length=