我有一个关于切片、计数器、时间以及 Go 中令人费解的合并和排序的一般性问题。
我从在线实践练习中编写了一个小程序来了解 Go,我很困惑为什么我编写的解决方案会出错。
代码只是两个计数器切片,它们是按时间排序的,我决定尝试合并它,然后再次按与计数对应的时间排序。我已经完成了其余的代码,但合并让我感到困惑。
将提供代码片段供您阅读。
package main
import (
"fmt"
"time"
)
/*
Given Counter slices that are sorted by Time, merge the slices into one slice.
Make sure that counters with the same Time are merged and the Count is increased.
E.g:
A = [{Time: 0, Count: 5}, {Time:1, Count: 3}, {Time: 4, Count 7}]
B = [{Time: 1, Count: 9}, {Time:2, Count: 1}, {Time: 3, Count 3}]
merge(A, B) ==>
[{Time: 0, Count: 5}, {Time: 1: Count: 12}, {Time: 2, Count 1}, {Time: 3, Count: 3}, {Time: 4: Count: 7}]
Explain the efficiency of your merging.
*/
type Counter struct {
Time time.Time
Count uint64
}
var (
A = []Counter{
{Time: time.Unix(0, 0), Count: 5},
{Time: time.Unix(0, 1), Count: 3},
{Time: time.Unix(0, 4), Count: 7},
}
B = []Counter{
{Time: time.Unix(0, 0), Count: 5},
{Time: time.Unix(0, 1), Count: 12},
{Time: time.Unix(0, 2), Count: 1},
{Time: time.Unix(0, 3), Count: 3},
{Time: time.Unix(0, 4), Count: 7},
}
)
func merge(a, b []Counter) []Counter {
// Insert your code here
res1 := append(a) <--- ERROR?
res2 := append(b) <--- ERROR?
return nil
}
func main() {
AB := merge(A, B)
for _, c := range AB {
fmt.Println(c)
}
}
精慕HU
相关分类