Algorithm/릿코드(leetcode)
[릿코드] 349번 : Intersection of Two Arrays
jalha
2021. 5. 10. 22:40
leetcode.com/problems/intersection-of-two-arrays/
Intersection of Two Arrays - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
num1과 num2 정수 배열이 주어진다. 교집합인 요소들의 배열을 구하시오.
(순서는 상관없으며, 결과의 각 요소는 유니크하다.)
어떻게 풀까
Set의 retainAll이라는 교집합 함수를 사용한다.
구현
import java.util.*; class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> num1 = new HashSet<>(); Set<Integer> num2 = new HashSet<>(); // 배열을 List로 변환 List<Integer> arr = Arrays.stream(nums1).boxed().collect(Collectors.toList()); List<Integer> arr2 = Arrays.stream(nums2).boxed().collect(Collectors.toList()); num1.addAll(arr); num2.addAll(arr2); num1.retainAll(num2); int[] result = num1.stream().mapToInt(i -> i).toArray(); return result; } }