[Leetcode: 349] Intersection of Two Arrays

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[]로 변환하여 리턴한다

'코딩테스트 > [스파르타] 작심큰일 코테 챌린지' 카테고리의 다른 글

[Day 10] TIL  (1) 2025.08.15
[Day 8] TIL  (0) 2025.08.14
[Day 7] TIL  (0) 2025.08.12
[Day 6] TIL  (2) 2025.08.12
[Day 5] TIL  (2) 2025.08.08