[Algorithm] Min Max Stack
max Stack ALGORITHM min
2023-09-14 08:59:12 时间
Write a MinMaxStack class for a Min Max Stack. The class should support:
- Pushing and popping values on and off the stack.
- Peeking at the value at the top of the stack.
- Getting both the minimum and the maximum values in the stack at any given point in time.
All class methods, when considered independently, should run in constant time and with constant space.
// All operations below are performed sequentially.
MinMaxStack(): - // instantiate a MinMaxStack
push(5): -
getMin(): 5
getMax(): 5
peek(): 5
push(7): -
getMin(): 5
getMax(): 7
peek(): 7
push(2): -
getMin(): 2
getMax(): 7
peek(): 2
pop(): 2
pop(): 7
getMin(): 5
getMax(): 5
peek(): 5
package main
type MinMaxStack struct {
data []int
minMaxStack []entry
}
type entry struct {
max int
min int
}
func NewMinMaxStack() *MinMaxStack {
return &MinMaxStack{}
}
func (stack *MinMaxStack) Peek() int {
return stack.data[len(stack.data)-1]
}
func (stack *MinMaxStack) Pop() int {
stack.minMaxStack = stack.minMaxStack[:len(stack.minMaxStack)-1]
output := stack.data[len(stack.data)-1]
stack.data = stack.data[:len(stack.data)-1]
return output;
}
func (stack *MinMaxStack) Push(number int) {
newMinMax := entry{min: number, max: number}
if len(stack.minMaxStack) > 0 {
lastMinMax := stack.minMaxStack[len(stack.minMaxStack) - 1]
newMinMax.min = min(lastMinMax.min, number)
newMinMax.max = max(lastMinMax.max, number)
}
stack.minMaxStack = append(stack.minMaxStack, newMinMax)
stack.data = append(stack.data, number)
}
func (stack *MinMaxStack) GetMin() int {
return stack.minMaxStack[len(stack.minMaxStack)-1].min
}
func (stack *MinMaxStack) GetMax() int {
return stack.minMaxStack[len(stack.minMaxStack)-1].max
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
相关文章
- centos8平台nginx服务配置打开文件限制max open files limits
- max file descriptors [4096] for elasticsearch process likely too low, increase to at least [65536]
- [Algorithm] Min Max Stack
- [Functional Programming] Find max / min value by using Ramda
- Nginx max_fails和fail_timeout配置不合理,造成服务故障
- 关于 Node.js 参数 max-old-space-size
- Database之SQLSever:SQL命令实现四则运算、desc降序、like模糊查询、distinct去重、MAX/MIN/SUM/AVG/COUNT/GROUP/having等案例之详细攻略
- WordPress Import 上传的文件尺寸超过php.ini中定义的upload_max_filesize值-->解决方法。
- 内置函数:max 用法
- LabVIEW如何修复或重置NI MAX数据库文件
- LabVIEW中NI MAX中缺少串口
- tensorflow knn 预测房价 注意有 Min-Max Scaling
- torch.max()综合