게으른개발너D
[Generator, Array] Nested Array Generator (feat. flat) 본문
https://leetcode.com/problems/nested-array-generator/description/
Nested Array Generator - LeetCode
Can you solve this real interview question? Nested Array Generator - Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal. A multi-dimensional array is a recursive data st
leetcode.com
Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal.
A multi-dimensional array is a recursive data structure that contains both integers and other multi-dimensional arrays.
inorder traversal iterates over each array from left to right, yielding any integers it encounters or applying inorder traversal to any arrays it encounters.
Example 1:
Input: arr = [[[6]],[1,3],[]]
Output: [6,1,3]
Explanation:
const generator = inorderTraversal(arr);
generator.next().value; // 6
generator.next().value; // 1
generator.next().value; // 3
generator.next().done; // true
Example 2:
Input: arr = []
Output: []
Explanation: There are no integers so the generator doesn't yield anything.
Constraints:
- 0 <= arr.flat().length <= 105
- 0 <= arr.flat()[i] <= 105
- maxNestingDepth <= 105
solution
/**
* @param {Array} arr
* @return {Generator}
*/
var inorderTraversal = function*(arr) {
arr = arr.flat(Infinity);
let i = 0;
while(i < arr.length) {
yield arr[i];
i++;
}
};
/**
* const gen = inorderTraversal([1, [2, 3]]);
* gen.next().value; // 1
* gen.next().value; // 2
* gen.next().value; // 3
*/
solution2) 재귀를 이용한 방법
var inorderTraversal = function*(arr) {
for (const element of arr) {
if (Array.isArray(element)) {
yield* inorderTraversal(element);
} else {
yield element;
}
}
}
'알고리즘 > 과제' 카테고리의 다른 글
[Class, Object] Event Emitter (0) | 2023.07.04 |
---|---|
[Function, prototype] Call Function with Custom Context (prototype 함수 안에 prototype 정의하기) ⭐️ (0) | 2023.07.04 |
[Array, prototype] Group By ⭐️ (0) | 2023.07.04 |
[Function] Debounce ⭐️ (0) | 2023.07.04 |
[Class] Calculator with Method Chaining (method에 return 값) ⭐️ (0) | 2023.07.04 |