๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
TIL๐Ÿ”ฅ/์ฝ”๋”ฉํ…Œ์ŠคํŠธ

[ํ•ญํ•ด99ํด๋Ÿฝ] Java ๋น„๊ธฐ๋„ˆ_Day 16 Intersection of Two Arrays

by hk713 2025. 4. 21.

์˜ค๋Š˜์˜ ๋ฌธ์ œ >> https://leetcode.com/problems/intersection-of-two-arrays/description/

 

[ ์ƒ๊ฐ ํ๋ฆ„ ]

์ผ๋‹จ ๊ฐ ๋ฐฐ์—ด์„ Set์œผ๋กœ ๋งŒ๋“ค์–ด์„œ ์ค‘๋ณต ์ œ๊ฑฐํ•˜๊ณ ,

๋‘๊ฐœ ๋‹ค ์†ํ•˜๋Š” ์›์†Œ๋งŒ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค..!

 

[ Java ]

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        for(int num: nums1){
            set1.add(num);
        }

        Set<Integer> resultSet = new HashSet<>();
        for(int num:nums2){
            if(set1.contains(num)){
                resultSet.add(num);
            }
        }

        int[] answer = new int[resultSet.size()];
        int i = 0;
        for(int num: resultSet){
            answer[i++] = num;
        }
        return answer; 
    }
}

 

๋Œ“๊ธ€