From a429c2f1ea30b4926a685f98925f304586d30a9f Mon Sep 17 00:00:00 2001 From: youze Date: Sun, 27 Mar 2022 18:08:52 +0800 Subject: [PATCH] sulution in go for 2208 --- .../README.md | 27 ++++++++++++++++--- .../Solution.go | 21 +++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) create mode 100644 solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.go diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md index d34d24641df4d..594cd392fd6a7 100644 --- a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md @@ -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 } ``` diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.go b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.go new file mode 100644 index 0000000000000..a8b76a443442d --- /dev/null +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/Solution.go @@ -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 }