-
Notifications
You must be signed in to change notification settings - Fork 355
/
Copy pathnested_list_weight_sum_ii.rb
67 lines (59 loc) · 1.5 KB
/
nested_list_weight_sum_ii.rb
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
#
#class NestedInteger
# def is_integer()
# """
# Return true if this NestedInteger holds a single integer, rather than a nested list.
# @return {Boolean}
# """
#
# def get_integer()
# """
# Return the single integer that this NestedInteger holds, if it holds a single integer
# Return nil if this NestedInteger holds a nested list
# @return {Integer}
# """
#
# def set_integer(value)
# """
# Set this NestedInteger to hold a single integer equal to value.
# @return {Void}
# """
#
# def add(elem)
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# @return {Void}
# """
#
# def get_list()
# """
# Return the nested list that this NestedInteger holds, if it holds a nested list
# Return nil if this NestedInteger holds a single integer
# @return {NestedInteger[]}
# """
# @param {NestedInteger[]} nested_list
# @return {Integer}
def depth_sum_inverse(nested_list)
h = {}
lvl = 0
while nested_list.any?
q = []
lvl+=1
h[lvl] = 0
nested_list.each do |n|
if n.is_integer()
h[lvl] += n.get_integer
else
q << n.get_list()
end
end
nested_list = q.flatten
end
sum = 0
h.each do |k, v|
sum += ((lvl-k+1) * v)
end
sum
end