forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-visible-people-in-a-queue.py
42 lines (39 loc) · 1.09 KB
/
number-of-visible-people-in-a-queue.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
# Time: O(n)
# Space: O(n)
class Solution(object):
def canSeePersonsCount(self, heights):
"""
:type heights: List[int]
:rtype: List[int]
"""
result = [0]*len(heights)
stk = []
for i, h in enumerate(heights):
while stk and heights[stk[-1]] < h:
result[stk.pop()] += 1
if stk:
result[stk[-1]] += 1
if stk and heights[stk[-1]] == h:
stk.pop()
stk.append(i)
return result
# Time: O(n)
# Space: O(n)
class Solution2(object):
def canSeePersonsCount(self, heights):
"""
:type heights: List[int]
:rtype: List[int]
"""
result = [0]*len(heights)
stk = []
for i in reversed(xrange(len(heights))):
cnt = 0
while stk and heights[stk[-1]] < heights[i]:
stk.pop()
cnt += 1
result[i] = cnt+1 if stk else cnt
if stk and heights[stk[-1]] == heights[i]:
stk.pop()
stk.append(i)
return result