Skip to content

Commit 7be8b9e

Browse files
authored
feat: add golang solution to lc problem: No.2208 (#775)
No.2208.Minimum Operations to Halve Array Sum
1 parent c255882 commit 7be8b9e

File tree

3 files changed

+69
-6
lines changed

3 files changed

+69
-6
lines changed

solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,30 @@ nums 的和减小了 31 - 14.5 = 16.5 ,减小的部分超过了初始数组和
7979

8080
```
8181

82-
### **...**
83-
84-
```
82+
### **Go**
83+
84+
```go
85+
func halveArray(nums []int) (ans int) {
86+
half := 0
87+
for i := range nums {
88+
nums[i] <<= 20
89+
half += nums[i]
90+
}
91+
h := hp{nums}
92+
heap.Init(&h)
93+
for half >>= 1; half > 0; ans++ {
94+
half -= h.IntSlice[0] >> 1
95+
h.IntSlice[0] >>= 1
96+
heap.Fix(&h, 0)
97+
}
98+
return
99+
}
100+
101+
type hp struct{ sort.IntSlice }
102+
103+
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
104+
func (hp) Push(interface{}) {}
105+
func (hp) Pop() (_ interface{}) { return }
85106

86107
```
87108

solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README_EN.md

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,30 @@ It can be shown that we cannot reduce the sum by at least half in less than 3 op
7171

7272
```
7373

74-
### **...**
75-
76-
```
74+
### **Go**
75+
76+
```go
77+
func halveArray(nums []int) (ans int) {
78+
half := 0
79+
for i := range nums {
80+
nums[i] <<= 20
81+
half += nums[i]
82+
}
83+
h := hp{nums}
84+
heap.Init(&h)
85+
for half >>= 1; half > 0; ans++ {
86+
half -= h.IntSlice[0] >> 1
87+
h.IntSlice[0] >>= 1
88+
heap.Fix(&h, 0)
89+
}
90+
return
91+
}
92+
93+
type hp struct{ sort.IntSlice }
94+
95+
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
96+
func (hp) Push(interface{}) {}
97+
func (hp) Pop() (_ interface{}) { return }
7798

7899
```
79100

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
func halveArray(nums []int) (ans int) {
2+
half := 0
3+
for i := range nums {
4+
nums[i] <<= 20
5+
half += nums[i]
6+
}
7+
h := hp{nums}
8+
heap.Init(&h)
9+
for half >>= 1; half > 0; ans++ {
10+
half -= h.IntSlice[0] >> 1
11+
h.IntSlice[0] >>= 1
12+
heap.Fix(&h, 0)
13+
}
14+
return
15+
}
16+
17+
type hp struct{ sort.IntSlice }
18+
19+
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
20+
func (hp) Push(interface{}) {}
21+
func (hp) Pop() (_ interface{}) { return }

0 commit comments

Comments
 (0)