Meta 面试题 #9 — 嵌套数组的加权和(深度和)

1次阅读
没有评论

Imagine an array that contains both integers and nested arrays, such as the following:
[8, 4, [5, [9], 3], 6].
The depth sum is described as the weighted sum of each integer, weighted by their respective depths. In the example, 8’s depth is 1, while 9’s is 3.
Given such an array, calculate its depth sum.

Examples

  • Input: [4, [5, 6]]
    Output: 4*1 + 2*5 + 2*6 = 26
  • Input: [8, 4, [5, [9], 3], 6]
    Output: 8*1 + 4*1 + 2*5 + 3*9 + 2*3 + 1*6 = 61

总结(含思路)
用 DFS 或 BFS 遍历嵌套结构,携带当前深度 d

  • 遇到整数,加到答案 ans += d * val
  • 遇到数组,递归 / 入队并把深度 +1。
    时间 O(N)(元素总数),空间 O(H)(递归深度或队列)。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 OpenAI、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0