Skip to content

sulution in go for 2208 #774

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,30 @@ nums 的和减小了 31 - 14.5 = 16.5 ,减小的部分超过了初始数组和

```

### **...**

```
### **Go**

```go
func halveArray(nums []int) (ans int) {
half := 0
for i := range nums {
nums[i] <<= 20
half += nums[i]
}
h := hp{nums}
heap.Init(&h)
for half >>= 1; half > 0; ans++ {
half -= h.IntSlice[0] >> 1
h.IntSlice[0] >>= 1
heap.Fix(&h, 0)
}
return
}

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (hp) Push(interface{}) {}
func (hp) Pop() (_ interface{}) { return }

```

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
func halveArray(nums []int) (ans int) {
half := 0
for i := range nums {
nums[i] <<= 20
half += nums[i]
}
h := hp{nums}
heap.Init(&h)
for half >>= 1; half > 0; ans++ {
half -= h.IntSlice[0] >> 1
h.IntSlice[0] >>= 1
heap.Fix(&h, 0)
}
return
}

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (hp) Push(interface{}) {}
func (hp) Pop() (_ interface{}) { return }