-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNested_List_Weight_Sum.java
More file actions
65 lines (48 loc) · 1.6 KB
/
Nested_List_Weight_Sum.java
File metadata and controls
65 lines (48 loc) · 1.6 KB
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
339. Nested List Weight Sum
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1''s at depth 2, one 2 at depth 1)
Example 2:
Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27)
//recursive
public int depthSum(List<NestedInteger> nestedList) {
return helper(nestedList, 1);
}
public int helper(List<NestedInteger> nestedList, int depth){
if(nestedList==null||nestedList.size()==0)
return 0;
int sum=0;
for(NestedInteger ni: nestedList){
if(ni.isInteger()){
sum += ni.getInteger() * depth;
}else{
sum += helper(ni.getList(), depth+1);
}
}
return sum;
}
///////////////////////////////////////////////
//iterative
public int depthSum(List<NestedInteger> nestedList) {
int sum=0;
LinkedList<NestedInteger> queue = new LinkedList<NestedInteger>();
LinkedList<Integer> depth = new LinkedList<Integer>();
for(NestedInteger ni: nestedList){
queue.offer(ni);
depth.offer(1);
}
while(!queue.isEmpty()){
NestedInteger top = queue.poll();
int dep = depth.poll();
if(top.isInteger()){
sum += dep*top.getInteger();
}else{
for(NestedInteger ni: top.getList()){
queue.offer(ni);
depth.offer(dep+1);
}
}
}
return sum;
}