Created
June 13, 2018 16:07
-
-
Save lkrych/4279fa848518b7630909b3cd04acf502 to your computer and use it in GitHub Desktop.
A more space-efficient implementation of stack with minimum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type stackWithMin struct { | |
data []int | |
minStack stack //utilizes the stack implementation we defined above! | |
} | |
func (s *stackWithMin) pop() int { | |
popped := s.data[len(s.data)-1] | |
s.data = s.data[:len(s.data)-1] | |
if popped == s.min() { //if you've popped the min, move it off the minStack! | |
s.minStack.pop() | |
} | |
return popped | |
} | |
func (s *stackWithMin) push(item int) { | |
s.data = append(s.data, item) | |
if item <= s.min() { //if the incoming item is less than the current min | |
s.minStack.push(item) | |
} | |
} | |
func (s *stackWithMin) min() int { | |
if s.minStack.isEmpty() { | |
return 100000000000000000 //really large number | |
} | |
return s.minStack.peek() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment