늘 겸손하게

LeetCode 2032 - Two Out of Three ( JavaScript ) 본문

코딩 문제/LeetCode

LeetCode 2032 - Two Out of Three ( JavaScript )

besforyou999 2021. 11. 15. 21:17

 

안녕하세요 besforyou입니다.

 

이번 글은 LeetCode 문제 2032 - Two Out of Three 풀이입니다.

 


문제 풀이

 

숫자가 배열에 존재하는지 존재하지 않는지가 중요한 문제이므로 집합을 사용하면 간편하게 구현 가능합니다.

 

각 배열의 원소들을 서로 다른 집합에 저장하는 동시에 배열에 존재하는 모든 원소를 담을 집합도 생성합니다.

 

그 후, 모든 원소를 담고 있는 집합의 원소를 순차적으로 참조하면서 현재 참조 중인 원소가 다른 몇 개의 집합에 존재하는 지를 세어 2개 이상의 집합에 존재한다면 정답 배열에 삽입합니다.

 

모든 원소를 한번씩 참조했다면 정답 배열을 반환합니다.

 


코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var twoOutOfThree = function(nums1, nums2, nums3) {
 
    const totalSet = new Set();
    const set1 = new Set();
    const set2 = new Set();
    const set3 = new Set();
    const ans = [];
 
    for (let i = 0 ; i < nums1.length ; i++) {
        let num = nums1[i];
        totalSet.add(num);
        set1.add(num);
    }
 
    for (let i = 0 ; i < nums2.length ; i++) {
        let num = nums2[i];
        totalSet.add(num);
        set2.add(num);
    }
 
    for (let i = 0 ; i < nums3.length ; i++) {
        let num = nums3[i];
        totalSet.add(num);
        set3.add(num);
    }
 
    for (let item of totalSet) {
        let count = 0;
        if (set1.has(item))count++;
        if (set2.has(item))count++;
        if (set3.has(item))count++;
        if (count >= 2) ans.push(item);
    }
    return ans;
};
 
cs

 

 


결과