-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
F_next_greater_element.py
66 lines (50 loc) · 1.51 KB
/
F_next_greater_element.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
def method1():
def createStack():
stack = []
return stack
def isEmpty(stack):
return len(stack) == 0
def push(stack, x):
stack.append(x)
def pop(stack):
if isEmpty(stack):
print("Error : stack underflow")
else:
return stack.pop()
def print_nge(arr):
s = createStack()
element = 0
next = 0
push(s, arr[0])
for i in range(1, len(arr), 1):
next = arr[i]
if isEmpty(s) == False:
element = pop(s)
while element < next:
print(str(element) + " -- " + str(next))
if isEmpty(s) == True:
break
element = pop(s)
if element > next:
push(s, element)
push(s, next)
while isEmpty(s) == False:
element = pop(s)
next = -1
print(str(element) + " -- " + str(next))
return print_nge
def method2(arr):
for i in range(0, len(arr), 1):
next = -1
for j in range(i + 1, len(arr), 1):
if arr[i] < arr[j]:
next = arr[j]
break
return str(arr[i]) + " -- " + str(next)
if __name__ == "__main__":
"""
from timeit import timeit
arr = [11, 13, 21, 3]
print(timeit(lambda: method1(), number=10000)) # 0.003247513002861524
print(timeit(lambda: method2(arr), number=10000)) # 0.008851628001139034
"""