LeetCode //2649. Nested Array Generator (Day 30 of LC JavaScript Challenage)

2649. 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 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 < = a r r . f l a t ( ) . l e n g t h < = 1 0 5 0 <= arr.flat().length <= 10^5 0<=arr.flat().length<=105
  • 0 < = a r r . f l a t ( ) [ i ] < = 1 0 5 0 <= arr.flat()[i] <= 10^5 0<=arr.flat()[i]<=105
  • m a x N e s t i n g D e p t h < = 1 0 5 maxNestingDepth <= 10^5 maxNestingDepth<=105

From: LeetCode
Link: 2649. Nested Array Generator


Solution:

Ideas:
The idea behind this code is to use a generator function to traverse a nested array. A generator function is a function that can be used to produce a sequence of values without actually storing all of the values in memory. This can be useful for large data sets, as it prevents the entire data set from being loaded into memory at once.
The inorderTraversal function works by recursively traversing the array. The recursive function checks if the current element is an array. If it is, it calls itself recursively to traverse the array. If it is not, it yields the element. This process continues until the entire array has been traversed.
Code:
/**
 * @param {Array} arr
 * @return {Generator}
 */
var inorderTraversal = function*(arr) {
    while (arr.length) {
    const current = arr.shift();

    if (Array.isArray(current)) {
      yield* inorderTraversal(current);
    } else {
      yield current;
    }
  }
};

/**
 * const gen = inorderTraversal([1, [2, 3]]);
 * gen.next().value; // 1
 * gen.next().value; // 2
 * gen.next().value; // 3
 */

你可能感兴趣的:(LeetCode,leetcode,javascript,算法)