Last active
January 17, 2022 16:47
-
-
Save CollinShoop/76cd9d33b99b716425dec72cc5d74b81 to your computer and use it in GitHub Desktop.
This file contains 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
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