You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].
Return true if it is possible to form the array arr from pieces. Otherwise, return false.
Example 1:
Input: arr = [15,88], pieces = [[88],[15]]
Output: true
Explanation: Concatenate [15] then [88]
Example 2:
Input: arr = [49,18,16], pieces = [[16,18,49]]
Output: false
Explanation: Even though the numbers match, we cannot reorder pieces[0].
Example 3:
Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
Output: true
Explanation: Concatenate [91] then [4,64] then [78]
출처 :https://leetcode.com/problems/check-array-formation-through-concatenation/description/
풀이
function canFormArray(arr: number[], pieces: number[][]): boolean {
let stack = [], map = new Map();
for (let el of pieces) map.set(el[0], el);
for (let el of arr) if (map.has(el)) stack = stack .concat(map.get(el));
return String(stack) == String(arr);
};
주어진 배열 arr와 여러 조각으로 나뉜 배열 pieces를 이용해 arr를 재구성할 수 있는지 확인하는 문제
예를 들어, arr = [1, 2, 3, 4, 5, 6]이고 pieces = [[1, 2], [3], [4, 5, 6]]인 경우
- map은 다음과 같이 설정:
1 => [1, 2]
3 => [3]
4 => [4, 5, 6]
- arr을 순회하면서 stack에 추가:
- arr의 첫 번째 요소 1은 map에 있으므로 stack에 [1, 2]가 추가.
- arr의 두 번째 요소 2는 map에 없으므로 무시.
- arr의 세 번째 요소 3은 map에 있으므로 stack에 [3]이 추가
- arr의 네 번째 요소 4는 map에 있으므로 stack에 [4, 5, 6]이 추가
- 최종적으로 stack은 [1, 2, 3, 4, 5, 6]이 되고, 이는 arr와 동일. 따라서 함수는 true를 반환
map.has(el)은 el이 map에 키로 존재하는지 여부를 확인하는 메서드로, true 또는 false를 반환
let pieces = [[1, 2], [3], [4, 5, 6]];
let map = new Map();
for (let el of pieces) {
map.set(el[0], el);
}
console.log(map.has(1)); // true
console.log(map.has(3)); // true
console.log(map.has(4)); // true
console.log(map.has(2)); // false
- map은 다음과 같이 설정:
1 => [1, 2]
3 => [3]
4 => [4, 5, 6]
map.has(1)은 true를 반환. 키 1이 map에 존재
map.has(3)도 true를 반환. 키 3이 map에 존재
map.has(4)도 true를 반환. 키 4가 map에 존재
반면, map.has(2)는 false를 반환. 키 2는 map에 존재하지 않음
map.get(key) 는 key에대한 밸류 값 반환
'LeetCode' 카테고리의 다른 글
| 1974. Minimum Time to Type Word Using Special Typewriter (0) | 2024.05.25 |
|---|---|
| 563. Binary Tree Tilt (0) | 2024.05.24 |
| 228. Summary Ranges / TypeScript (0) | 2024.05.20 |
| 2932. Maximum Strong Pair XOR I / TypeScript (0) | 2024.05.19 |
| 2562. Find the Array Concatenation Value / TypeScript (0) | 2024.05.18 |