Skip to content

Instantly share code, notes, and snippets.

@CollinShoop
Last active January 17, 2022 16:47
Show Gist options
  • Save CollinShoop/76cd9d33b99b716425dec72cc5d74b81 to your computer and use it in GitHub Desktop.
Save CollinShoop/76cd9d33b99b716425dec72cc5d74b81 to your computer and use it in GitHub Desktop.
func lastStoneWeight(stones []int) int {
h := &IntHeap{}
for _, val := range stones {
heap.Push(h, val)
}
for h.Len() > 1 {
var largest = heap.Pop(h).(int)
var smaller = heap.Pop(h).(int)
if largest != smaller {
heap.Push(h, largest-smaller)
}
}
if h.Len() > 0 {
return heap.Pop(h).(int)
}
return 0
}
type IntHeap []int
func (h IntHeap) Len() int {
return len(h)
}
func (h IntHeap) Less(i, j int) bool {
return h[i] > h[j]
}
func (h IntHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0:n-1]
return x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment