[LeetCode] Intersection of Two Arrays

아르당·2026년 1월 4일

LeetCode

목록 보기
74/134
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 정수 배열 nums1과 nums2가 주어졌을 때, 두 변수의 교집합을 배열로 반환해라. 결과의 각 요소들은 고유해야하고, 결과는 어떤 순서로든 반환할 수 있다.

Example

#1
Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output: [2]

#2
Input: nums 1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
Output: [9, 4]
Explanation: [4, 9] 또한 받아들인다.

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Solved

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> hs= new HashSet<>();

        for(int i = 0; i < nums1.length; i++) {
            hs.add(nums1[i]);
        }

        Set<Integer> res = new HashSet<>();

        for(int i = 0; i < nums2.length; i++) {
            if(hs.contains(nums2[i])) {
                res.add(nums2[i]);
            }
        }

        int[] arr = new int[res.size()];
        int i = 0;
        for(int el: res) {
            arr[i++] = el;
        }

        return arr;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글