Skip to content

Commit 9703342

Browse files
authored
Create diagonal-traverse-ii.py
1 parent fcff5f8 commit 9703342

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Python/diagonal-traverse-ii.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: O(m * n)
2+
# Space: O(m)
3+
4+
import itertools
5+
6+
7+
class Solution(object):
8+
def findDiagonalOrder(self, nums):
9+
"""
10+
:type nums: List[List[int]]
11+
:rtype: List[int]
12+
"""
13+
result, q, col = [], [], 0
14+
for i in xrange(len(nums)+max(itertools.imap(len, nums))-1):
15+
new_q = []
16+
if i < len(nums):
17+
q.append((i, 0))
18+
for r, c in reversed(q):
19+
result.append(nums[r][c])
20+
if c+1 < len(nums[r]):
21+
new_q.append((r, c+1))
22+
new_q.reverse()
23+
q = new_q
24+
return result
25+
26+
27+
# Time: O(m * n)
28+
# Space: O(m * n)
29+
class Solution2(object):
30+
def findDiagonalOrder(self, nums):
31+
"""
32+
:type nums: List[List[int]]
33+
:rtype: List[int]
34+
"""
35+
result = []
36+
for i, row in enumerate(nums):
37+
for j, num in enumerate(row):
38+
if len(result) <= i+j:
39+
result.append([])
40+
result[i+j].append(num)
41+
return [num for row in result for num in reversed(row)]

0 commit comments

Comments
 (0)