solved with stack method O(n^2)

This commit is contained in:
Jacob Delgado 2023-09-28 18:02:08 -07:00
parent 4d8fd333e4
commit 7da5e88c64
2 changed files with 49 additions and 43 deletions

View File

@ -4,43 +4,55 @@ class Solution(object):
:type temperatures: List[int] :type temperatures: List[int]
:rtype: List[int] :rtype: List[int]
""" """
count = 0 # Two pointer method, timed out O(n^2)
warmer_days = [] # count = 0
l = 0 # warmer_days = []
r = 1 # l = 0
while l < r: # r = 1
# print(r) # while l < r:
if r == len(temperatures)-1: # # print(r)
if l != len(temperatures)-2: # if r == len(temperatures)-1:
if temperatures[r] > temperatures[l]: # if l != len(temperatures)-2:
count += 1 # if temperatures[r] > temperatures[l]:
warmer_days.append(count) # count += 1
else: # warmer_days.append(count)
warmer_days.append(0) # else:
l += 1 # warmer_days.append(0)
r = l + 1 # l += 1
count = 0 # r = l + 1
else: # count = 0
if temperatures[r] > temperatures[l]: # else:
count += 1 # if temperatures[r] > temperatures[l]:
warmer_days.append(count) # count += 1
else: # warmer_days.append(count)
warmer_days.append(0) # else:
break # warmer_days.append(0)
elif temperatures[r] > temperatures[l]: # break
count += 1 # elif temperatures[r] > temperatures[l]:
warmer_days.append(count) # count += 1
count = 0 # warmer_days.append(count)
l += 1 # count = 0
r = l + 1 # l += 1
else: # r = l + 1
r += 1 # else:
count += 1 # r += 1
warmer_days.append(0) # count += 1
return warmer_days # warmer_days.append(0)
# return warmer_days
# Stack Method
res = [0] * len(temperatures)
stack = [] # contains pair of [temp, index]
for i, t in enumerate(temperatures): #looping through temperatures array and their index
while stack and t > stack[-1][0]: # is our stack empty and is our temperature greater than the top of our stack
stackT, stackInd = stack.pop()
res[stackInd] = (i - stackInd) # compute the days it took us to find a higher temperature
stack.append((t,i)) # append to the stack the temperature and index
return res
obj = Solution() obj = Solution()
# print(obj.dailyTemperatures([73,74,75,71,69,72,76,73])) # [1,1,4,2,1,1,0,0] print(obj.dailyTemperatures([73,74,75,71,69,72,76,73])) # [1,1,4,2,1,1,0,0]
# print(obj.dailyTemperatures([30,40,50,60])) # [1,1,1,0] # print(obj.dailyTemperatures([30,40,50,60])) # [1,1,1,0]
# print(obj.dailyTemperatures([55,38,53,81,61,93,97,32,43,78])) # [3,1,1,2,1,1,0,1,1,0] # print(obj.dailyTemperatures([55,38,53,81,61,93,97,32,43,78])) # [3,1,1,2,1,1,0,1,1,0]
print(obj.dailyTemperatures([77,77,77,77,77,41,77,41,41,77])) # [0,0,0,0,0,1,0,2,1,0] # print(obj.dailyTemperatures([77,77,77,77,77,41,77,41,41,77])) # [0,0,0,0,0,1,0,2,1,0]

View File

@ -1,7 +1 @@
elif r == len(temperatures)-1: 0]*len(temperatures)
if l != len(temperatures)-2:
l += 1
r = l + 1
else:
warmer_days.append(0)
break