GoLang, 2 slices with separate receivers


  • 1
    A
    type intStack struct {
    	s []int
    }
    
    type MinStack struct {
    	s1, s2 intStack
    }
    
    func (s *intStack) empty() bool {
    	return len(s.s) == 0
    }
    
    func (s *intStack) push(v int) {
    	s.s = append(s.s, v)
    }
    
    func (s *intStack) pop() {
    	if s.empty() {
    		return
    	}
    	s.s = s.s[:len(s.s)-1]
    }
    
    func (s *intStack) top() int {
    	if s.empty() {
    		return 0
    	}
    	return s.s[len(s.s)-1]
    }
    
    func Constructor() MinStack {
    	return MinStack{}
    }
    
    func (this *MinStack) Push(x int) {
    	this.s1.push(x)
    	if this.s2.empty() || x <= this.s2.top() {
    		this.s2.push(x)
    	}
    }
    
    func (this *MinStack) Pop() {
    	if this.Top() == this.GetMin() {
    		this.s2.pop()
    	}
    	this.s1.pop()
    }
    
    func (this *MinStack) Top() int {
    	return this.s1.top()
    }
    
    func (this *MinStack) GetMin() int {
    	return this.s2.top()
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.