PLOD

[Leetcode] 349. Intersection of Two Arrays 본문

대외 활동 및 IT 지식/알고리즘 문제 풀이 정리

[Leetcode] 349. Intersection of Two Arrays

훌룽이 2026. 4. 13. 18:12

🔗 문제 링크

https://leetcode.com/problems/intersection-of-two-arrays/description/

 

Intersection of Two Arrays - LeetCode

Can you solve this real interview question? Intersection of Two Arrays - Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.   Example 1: In

leetcode.com

 

✅ 코드

import java.io.*;
import java.util.*;

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

        int n = nums1.length;
        int m = nums2.length;

        Arrays.sort(nums1);
        Arrays.sort(nums2);

        if(n >= m){
            for(int i = 0; i < m ; i++){
                if(Arrays.binarySearch(nums1,nums2[i]) > -1){
                    set.add(nums2[i]);
                }
            }
        }else{
            for(int i = 0 ; i < n ; i++){
                if(Arrays.binarySearch(nums2,nums1[i]) > -1){
                    set.add(nums1[i]);
                }
            }
        }

        int[] answer = set.stream()
                  .mapToInt(Integer::intValue)
                  .toArray();

        return answer; 
    }
}

💡 배운 점 & 느낀 점

1. Arrays.binarySearch → 배열에서 이진탐색을 하기 위해서는 반드시 먼저 정렬(Arrays.sort())를 진행해줘야 한다

Comments