Daily 온도를 나타내는 an array of integers temperatures
가 입력되면, 마찬가지로 an array of integers answer
를 반환하는데, answer[i]
는 temperatures[i]
가 이후 요소 중 더 높은 수(온도)가 되는 지점과의 offset(the number of days you have to wait)이다.
만약 temperatures[i]
이후 데이터가 없거나, 큰 수가 없을 경우에는 해당 answer[i]
는 0이 된다.
1 ≤ temperatures.length
≤ 10^5,
30 ≤ temperatures[i]
≤ 100
temperatures.length
이고, O(n^2) 이상의 복잡도를 갖는 알고리즘은 사용할 수 없다.def dailyTemperatures(temperatures):
# 1. List answer를 선언하고 초기값으로 0을 할당한다.
# 이렇게 하면 이후 더 높은 수가 나오지 않는 경우나, 마지막 요소일 경우 0을 추가로 할당하지 않아도 된다.
answer = [0] * len(temperatures)
# 2. 다음 온도가 현재 온도보다 높지 않을 경우 저장해두기 위한 stack을 만들어 놓는다.
stack = []
# 3. enumerate 함수를 활용하여 idx와 value를 동시에 순회하면서
for cur_day, cur_temp in enumerate(temperatures):
# 4. stack에 저장된 온도 정보가 있고, stack의 top의 온도가 현재 온도보다 낮다면
while stack and stack[-1][1] < cur_temp:
# 5. stack의 top을 pop, 저장된 idx를 추출하고
saved_day, _ = stack.pop()
# 6. answer의 해당 idx에 현재 순회중인 idx와의 offset으로 대체한다.
answer[saved_day] = cur_day - saved_day
# 7, 현재 순회중인 데이터의 idx와 온도를 스택에 넣는다.
stack.append((cur_day, cur_temp))
return answer
temperatures.length
와 stack에 저장될 data의 수는 연관성이 없다.