class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
int idx = 0;
for(int num : nums1) {
set1.add(num);
}
for(int num : nums2) {
if(set1.contains(num)) {
set2.add(num);
}
}
int[] arr = new int[set2.size()];
int i=0;
for(int num : set2) {
arr[i++] = num;
}
return arr;
}
}
- 첫 번째 int[] nums1을 HashSet에 저장하여 중복을 없앤다.
- 두 번째 int[] nums2은 nums1을 저장한 set1에 포함되는 값만 HashSet에 저장한다.
- 교집합이면서 중복 X, 순서 상관 X => Set을 사용한다.
- 문제에서 원하는 output이 int 배열이므로 결과를 담은 set2 -> int[]로 변환하여 리턴한다