-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path22.flatten-list.py
86 lines (79 loc) · 1.78 KB
/
22.flatten-list.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Tag: Simulation
# Time: O(N)
# Space: O(N)
# Ref: -
# Note: -
# Given a list, each element in the list can be a list or an integer.Flatten it into a simply list with integers.
#
# **Example 1:**
#
# Input:
# ```
# list = [[1,1],2,[1,1]]
# ```
# Output:
# ```
# [1,1,2,1,1]
# ```
# Explanation:
#
# Flatten it into a simply list with integers.
#
# **Example 2:**
#
# Input:
# ```
# list = [1,2,[1,2]]
# ```
# Output:
# ```
# [1,2,1,2]
# ```
# Explanation:
#
# Flatten it into a simply list with integers.
#
# **Example 3:**
#
# Input:
# ```
# list = [4,[3,[2,[1]]]]
# ```
# Output:
# ```
# [4,3,2,1]
# ```
# Explanation:
#
# Flatten it into a simply list with integers.
#
# If the element in the given list is a list, it can contain list too.
from collections import deque
class Solution(object):
# @param nestedList a list, each element in the list
# can be a list or integer, for example [1,2,[1,2]]
# @return {int[]} a list of integer
def flatten(self, nestedList):
# Write your code here
res = []
for x in nestedList:
if isinstance(x, list):
res += self.flatten(x)
else:
res.append(x)
return res
class Solution(object):
# @param nestedList a list, each element in the list
# can be a list or integer, for example [1,2,[1,2]]
# @return {int[]} a list of integer
def flatten(self, nestedList):
# Write your code here
res = []
stack = nestedList[::-1]
while len(stack) > 0:
cur = stack.pop()
if isinstance(cur, int):
res.append(cur)
else:
stack.extend(reversed(cur))
return res