【Liボタン】349. 2つの配列の交差
2 つの配列 nums1 と nums2 を指定すると、それらの共通部分を返します。出力内の各要素は一意である必要があります。出力結果の順序は無視できます。
例 1:
入力: nums1 = [1,2,2,1]、nums2 = [2,2]
出力: [2]
例 2:
入力: nums1 = [4,9,5]、nums2 = [9,4,9,8,4]
出力: [9,4]
説明: [4,9] も合格です
ヒント:
1 <= nums1.length、nums2.length <= 1000
0 <= nums1[i]、nums2[i] <= 1000
答え
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
//方法1:将结果集合转为数组
return resSet.stream().mapToInt(x -> x).toArray();
//方法2:另外申请一个数组存放setRes中的元素,最后返回数组
int[] arr = new int[resSet.size()];
int j = 0;
for(int i : resSet){
arr[j++] = i;
}
return arr;
}
}