일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- react
- vscode
- frontend
- 동적 계획법
- DP
- 그레이들
- DFS
- 자바
- Python
- db
- BFS
- 프로그래머스
- 다이나믹 프로그래밍
- LeetCode
- 안드로이드
- Graph
- network
- Database
- Algorithm
- CS
- java
- Javascript
- VIM
- 리트코드
- 백준
- TypeScript
- git
- Redux
- 알고리즘
- Data Structure
Archives
- Today
- Total
늘 겸손하게
LeetCode 2032 - Two Out of Three ( JavaScript ) 본문
안녕하세요 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 |
결과
'코딩 문제 > LeetCode' 카테고리의 다른 글
LeetCode 1347 - Minimum Number of Steps to Make Two Strings Anagram ( JavaScript ) (0) | 2021.11.16 |
---|---|
LeetCode 890 - Find and Replace Return ( JavaScript ) (0) | 2021.11.15 |
LeetCode 1207 - Unique Number of Occurrences ( JavaScript ) (0) | 2021.11.13 |
LeetCode 111 - Minimum Depth of Binary Tree ( JavaScript ) (0) | 2021.11.01 |
LeetCode 1277 - Count Square Submatrices with All Ones (0) | 2021.08.30 |