![[99클럽 코테 스터디 TIL 22일차] 349. Intersection of Two Arrays 해설 및 풀이 (Java)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FpVpGB%2FbtsNtpTdD5D%2FAAAAAAAAAAAAAAAAAAAAADCJhx24O3IbN-g-7FyQNSvWZaJBAPdKwTpyHPpT7FhZ%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1753973999%26allow_ip%3D%26allow_referer%3D%26signature%3DLxHaOosAKQdztOmw9CMdCuErU%252B4%253D)
[99클럽 코테 스터디 TIL 22일차] 349. Intersection of Two Arrays 해설 및 풀이 (Java)Study/코딩 테스트2025. 4. 21. 23:59
Table of Contents
반응형
LeetCode 349. Intersection of Two Arrays
https://leetcode.com/problems/intersection-of-two-arrays/description/
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:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
문제 유형
Array Hash Table Two Pointers Binary Search Sorting
풀이 방법 도출
- 먼저 nums1을 Set에 저장해서 중복을 제거합니다.
- nums2를 순회하면서 nums1의 Set에 존재하는 값만 resultSet에 저장합니다.
- 마지막으로 Set을 배열로 변환하여 결과를 반환합니다.
시간 복잡도
- O(n + m)
핵심 코드 삽입 및 설명
import java.util.*;
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// Set을 사용하여 nums1의 중복을 제거하고 저장
Set<Integer> set1 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
// 결과를 저장할 Set
Set<Integer> resultSet = new HashSet<>();
for (int num : nums2) {
// nums2의 요소가 nums1에도 있다면 결과 Set에 추가
if (set1.contains(num)) {
resultSet.add(num);
}
}
// 결과 Set을 배열로 변환
int[] result = new int[resultSet.size()];
int i = 0;
for (int num : resultSet) {
result[i++] = num;
}
return result;
}
}
반응형
'Study > 코딩 테스트' 카테고리의 다른 글
[백준] 2667번 단지번호붙이기 해설 및 풀이 (Python) (0) | 2025.04.22 |
---|---|
[프로그래머스] Lv1. 체육복 해설 및 풀이 (Python) (0) | 2025.04.22 |
[99클럽 코테스터디 TIL 19일차] 백준 25325번 학생 인기도 측정 해설 및 풀이 (Java) (0) | 2025.04.18 |
[LeetCode] 643. Maximum Average Subarray I 해설 및 풀이 (Python) (0) | 2025.04.18 |
[99클럽 코테스터디 TIL 18일차] 백준 29723번 브실이의 입시전략 해설 및 풀이 (Java) (0) | 2025.04.17 |
@Dev Chu :: Log_Double 7
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!