처음부터 차근차근

[LeetCode] Intersection of Two Arrays 본문

코딩테스트/Javascript

[LeetCode] Intersection of Two Arrays

HangJu_95 2023. 12. 27. 00:48
728x90

문제 링크

https://leetcode.com/problems/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:

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.

 

간단하게 두 개의 배열이 주어졌을 때, 교집합을 구하는 방법입니다.

스파르타코딩클럽에서는 BS를 통해 구하였지만, 저는 다른 방법으로 구현하였습니다.

내 풀이

function intersection(nums1: number[], nums2: number[]): number[] {
    const set1 = new Set(nums1);
    const set2 = new Set(nums2);
    const result = new Set();
    for (const value of set1) {
        if (set2.has(value)) result.add(value);
    }
    return [...result] as number[];
};

 

저는 Set을 통해 문제를 풀었습니다.

Set은 기본적으로 수학의 집합을 표한하기 위해 사용되는 자료구조입니다.

또한 Set은 중복자료가 허용되지 않으며, 기본적으로 Hash Table로 구현하기 때문에 탐색, 삽입, 삭제가 굉장히 빠릅니다.

 

[Deep Dive] 37. Set과 Map

Set과 Map의 특징 Map과 Set 모두 Hash를 통해 구현합니다. 두 가지의 자료구조 특징 중 하나는 우리가 자주 사용하는 Array나 Object에 비해 데이터 삽입, 삭제, 조회를 할 경우 시간복잡도가 낮다는 점

hangju95.tistory.com

따라서, Set.has 메서드를 사용하여 공통되는 인자가 있다면, Result에 추가하는 방식을 선택하였습니다.

다른 사람의 풀이

이 방법은 Javascript Deep Dive를 통해 풀었습니다.

오늘 배운 점

Set을 통해 실제 알고리즘 문제를 풀어봤습니다.

집합 관련된 문제를 풀 때 구현하기 매우 간단하며, 시간 복잡도 또한 빠르다는 것을 체감하였습니다.

 

 

 

 

'코딩테스트 > Javascript' 카테고리의 다른 글

[프로그래머스] 네트워크  (1) 2024.01.02
[프로그래머스] 가장 큰 수  (1) 2023.12.27
[LeetCode] Binary Search  (0) 2023.12.27
[프로그래머스] Lv2 더 맵게  (0) 2023.11.16
[프로그래머스] Lv2 의상  (1) 2023.11.01