File tree Expand file tree Collapse file tree 3 files changed +69
-6
lines changed
solution/2200-2299/2208.Minimum Operations to Halve Array Sum Expand file tree Collapse file tree 3 files changed +69
-6
lines changed Original file line number Diff line number Diff line change @@ -79,9 +79,30 @@ nums 的和减小了 31 - 14.5 = 16.5 ,减小的部分超过了初始数组和
79
79
80
80
```
81
81
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 }
85
106
86
107
```
87
108
Original file line number Diff line number Diff 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
71
71
72
72
```
73
73
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 }
77
98
78
99
```
79
100
Original file line number Diff line number Diff line change
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 }
You can’t perform that action at this time.
0 commit comments