Skip to content

Commit 9ce8f9b

Browse files
Create 1046-last-stone-weight.go
1 parent 96407d9 commit 9ce8f9b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

go/1046-last-stone-weight.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
type IntHeap []int
2+
3+
func (h IntHeap) Len() int { return len(h) }
4+
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
5+
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
6+
func (h *IntHeap) Push(x interface{}) {*h = append(*h, x.(int))}
7+
func (h *IntHeap) Pop() interface{} {
8+
old := *h
9+
n := len(old)
10+
x := old[n-1]
11+
*h = old[0 : n-1]
12+
return x
13+
}
14+
15+
type KthLargest struct {
16+
minHeap *IntHeap
17+
k int
18+
}
19+
20+
func lastStoneWeight(_stones []int) int {
21+
for s := 0; s < len(_stones); s++ {
22+
_stones[s] *= -1
23+
}
24+
stones := IntHeap(_stones)
25+
heap.Init(&stones)
26+
27+
for len(stones) > 1 {
28+
first, _ := heap.Pop(&stones).(int)
29+
second, _ := heap.Pop(&stones).(int)
30+
if second > first {
31+
heap.Push(&stones, first - second)
32+
}
33+
}
34+
stones = append(stones, 0)
35+
return abs(stones[0])
36+
}
37+
38+
func abs(x int) int {
39+
if x < 0 {
40+
return -x
41+
}
42+
return x
43+
}

0 commit comments

Comments
 (0)