合并排序计数器切片

我有一个关于切片、计数器、时间以及 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)

  }

}


繁星coding
浏览 93回答 1
1回答

精慕HU

要解决有关附加和排序数组的问题,您只需将一个数组的片段附加到另一个数组,如下所示:result := append(a, b...)要根据 unix time 等内部结构类型对数组进行排序,最好的办法是创建切片的自定义类型并实现 sort.Interface 的方法。示例是:type ByTime []Counterfunc (c ByTime) Len() int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ return len(c) }func (c ByTime) Swap(i, j int)&nbsp; &nbsp; &nbsp; { c[i], c[j] = c[j], c[i] }func (c ByTime) Less(i, j int) bool { return c[i].Time.Before(c[j].Time) }然后只打电话sort.Sort(ByTime(result))完整示例: https: //play.golang.org/p/L9_aPRlQsss但请注意,我并没有解决您的编码练习如何基于内部指标合并两个数组,仅将一个附加到另一个。你需要在你的家庭作业中做一些工作;-) 这仍然会产生排序的(不是元素合并的)切片:{1970-01-01 00:00:00 +0000 UTC 5}{1970-01-01 00:00:00.000000001 +0000 UTC 3}{1970-01-01 00:00:00.000000001 +0000 UTC 9}{1970-01-01 00:00:00.000000002 +0000 UTC 1}{1970-01-01 00:00:00.000000003 +0000 UTC 3}{1970-01-01 00:00:00.000000004 +0000 UTC 7}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go