Skip to content

Commit 210a03e

Browse files
authored
Create number-of-visible-people-in-a-queue.py
1 parent 5faffd1 commit 210a03e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def canSeePersonsCount(self, heights):
6+
"""
7+
:type heights: List[int]
8+
:rtype: List[int]
9+
"""
10+
result = [0]*len(heights)
11+
stk = []
12+
for i, h in enumerate(heights):
13+
while stk and heights[stk[-1]] <= h:
14+
result[stk.pop()] += 1
15+
if stk:
16+
result[stk[-1]] += 1
17+
stk.append(i)
18+
return result
19+
20+
21+
# Time: O(n)
22+
# Space: O(n)
23+
class Solution2(object):
24+
def canSeePersonsCount(self, heights):
25+
"""
26+
:type heights: List[int]
27+
:rtype: List[int]
28+
"""
29+
result = [0]*len(heights)
30+
stk = []
31+
for i in reversed(xrange(len(heights))):
32+
cnt = 0
33+
while stk and heights[stk[-1]] < heights[i]:
34+
stk.pop()
35+
cnt += 1
36+
result[i] = cnt+1 if stk else cnt
37+
stk.append(i)
38+
return result

0 commit comments

Comments
 (0)