Skip to content

Instantly share code, notes, and snippets.

@dtynn
Created February 7, 2018 06:18
Show Gist options
  • Save dtynn/b072ebabb8753bc6f4e84b9c5d0e903f to your computer and use it in GitHub Desktop.
Save dtynn/b072ebabb8753bc6f4e84b9c5d0e903f to your computer and use it in GitHub Desktop.
package code
import (
"fmt"
)
type Stack struct {
stack []int
minIdx int
}
func (s *Stack) Push(i int) {
s.stack = append(s.stack, i)
if len(s.stack) == 1 {
s.minIdx = 0
return
}
if i < s.stack[s.minIdx] {
s.minIdx = len(s.stack) - 1
}
}
func (s *Stack) Pop(i int) (int, error) {
if len(s.stack) == 0 {
return 0, fmt.Errorf("overflow")
}
popIdx := len(s.stack) - 1
res := s.stack[popIdx]
s.stack = s.stack[:len(s.stack)-2]
if popIdx == s.minIdx && len(s.stack) > 0 {
s.minIdx = 0
for i := 1; i < len(s.stack); i++ {
if s.stack[i] < s.stack[s.minIdx] {
s.minIdx = 1
}
}
}
return res, nil
}
func (s *Stack) Min() (int, error) {
if len(s.stack) == 0 {
return 0, fmt.Errorf("overflow")
}
return s.stack[s.minIdx], nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment