오늘 배웠습니다: 최소-최대 스택
9225 단어 pythonalgorithmswebdevbeginners
문제 설명
다음 기능을 사용하여 Min-Max 스택에 대한 MinMaxStack 클래스를 작성하십시오.
샘플 입력 및 출력
stack = MinMaxStack()
stack.push(5) # min: 5, max: 5, current value: 5
stack.push(7) # min: 5, max: 7, current value: 7
stack.push(2) # min: 2, max: 7, current value: 2
stack.pop(2)
stack.pop(7) # min: 5, max: 5, current value: 5
코드 #1
class MinMaxStack:
def __init__(self):
self.stack = []
def peek(self):
if len(self.stack) == 0:
return None
else:
return self.stack[len(self.stack) - 1]['value']
def pop(self):
if len(self.stack) == 0:
return None
else:
return self.stack.pop()['value']
def push(self, number):
self.stack.append(
{
'value': number,
'min': self._calc_min(number),
'max': self._calc_max(number)
}
)
def get_min(self):
if len(self.stack) == 0:
return None
else:
return self.stack[len(self.stack) - 1]['min']
def get_max(self):
if len(self.stack) == 0:
return None
else:
return self.stack[len(self.stack) - 1]['max']
def _calc_min(self, number):
if len(self.stack) == 0:
return number
elif number < self.stack[len(self.stack) - 1]['min']:
return number
else:
return self.stack[len(self.stack) - 1]['min']
def _calc_max(self, number):
if len(self.stack) == 0:
return number
elif number > self.stack[len(self.stack) - 1]['max']:
return number
else:
return self.stack[len(self.stack) - 1]['max']
메모
stack = MinMaxStack()
stack.push(5) # min: 5, max: 5, current value: 5
stack.push(7) # min: 5, max: 7, current value: 7
stack.push(2) # min: 2, max: 7, current value: 2
stack.pop(2)
stack.pop(7) # min: 5, max: 5, current value: 5
class MinMaxStack:
def __init__(self):
self.stack = []
def peek(self):
if len(self.stack) == 0:
return None
else:
return self.stack[len(self.stack) - 1]['value']
def pop(self):
if len(self.stack) == 0:
return None
else:
return self.stack.pop()['value']
def push(self, number):
self.stack.append(
{
'value': number,
'min': self._calc_min(number),
'max': self._calc_max(number)
}
)
def get_min(self):
if len(self.stack) == 0:
return None
else:
return self.stack[len(self.stack) - 1]['min']
def get_max(self):
if len(self.stack) == 0:
return None
else:
return self.stack[len(self.stack) - 1]['max']
def _calc_min(self, number):
if len(self.stack) == 0:
return number
elif number < self.stack[len(self.stack) - 1]['min']:
return number
else:
return self.stack[len(self.stack) - 1]['min']
def _calc_max(self, number):
if len(self.stack) == 0:
return number
elif number > self.stack[len(self.stack) - 1]['max']:
return number
else:
return self.stack[len(self.stack) - 1]['max']
메모
크레딧
Reference
이 문제에 관하여(오늘 배웠습니다: 최소-최대 스택), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/anzhari/today-i-learned-min-max-stack-26f5텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)