-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestSmallestToLeft.py
More file actions
68 lines (54 loc) · 1.38 KB
/
Copy pathNearestSmallestToLeft.py
File metadata and controls
68 lines (54 loc) · 1.38 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
66
67
68
# arr: [1 ,3 ,2 ,4]
# ans: [-1 ,1 ,1 ,2]
#
# arr: [4 ,5 ,2 ,10 ,8]
# ans: [-1,4,-1,2,2]
# simple
def NSLSimple(arr):
length = len(arr)
for i in range(0, length):
ans = -1
for j in range(i - 1, -1, -1):
if arr[i] > arr[j]:
ans = arr[j]
break
print(arr[i], " - ", ans)
class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
return len(self.stack) == 0
def push(self, element):
self.stack.append(element)
def pop(self):
if self.isEmpty():
return -1
else:
return self.stack.pop()
def top(self):
return self.stack[-1]
def NSLStack(arr):
length = len(arr)
s = Stack()
ans = []
for i in range(0, length):
if s.isEmpty():
ans.append(-1)
else:
if s.top() < arr[i]:
ans.append(s.top())
else:
while not s.isEmpty() and s.top() >= arr[i]:
s.pop()
if s.isEmpty():
ans.append(-1)
else:
ans.append(s.top())
s.push(arr[i])
return ans
def main():
arr = [4, 5, 2, 10, 8]
NSLSimple(arr)
print(NSLStack(arr))
if __name__ == "__main__":
main()