1 回答
TA贡献1829条经验 获得超4个赞
如果目标是graph按成本对每个切片进行排序,则只需实现sort.Interfaceon []Graph,然后使用 for 循环遍历值。
type ByCost []Graph
func (gs *ByCost) Len() int { return len(gs) }
func (gs *ByCost) Less(i, j int) bool { return gs[i].cost < gs[j].cost }
func (gs *ByCost) Swap(i, j int) { gs[i], gs[j] = gs[j], gs[i] }
for _, v := range graph {
sort.Sort(ByCost(v))
如果您尝试按照中的成本总和排序的顺序遍历地图[]Graph,那将变得不那么干净。
type GraphKeyPairs struct {
key string
value []Graph
}
// Build a slice to store our map values
sortedGraph := make([]GraphKeyPairs, 0, len(graph))
for k,v := range graph {
// O(n)
gkp := GraphKeyPairs{key: k, value: v}
sortedGraph = append(sortedGraph, gkp)
}
type BySummedCost []GraphKeyPairs
func (gkp *BySummedCost) Len() int { return len(gkp) }
func (gkp *BySummedCost) Swap(i, j int) { gkp[i], gkp[j] = gkp[j], gkp[i] }
func (gkp *BySummedCost) Less(i, j int) bool {
// O(2n)
iCost, jCost := 0, 0
for _, v := range gkp[i].value {
iCost += v.cost
}
for _, v := range gkp[j].value {
jCost += v.cost
}
return iCost < jCost
}
sort.Sort(BySummedCost(sortedGraph))
- 1 回答
- 0 关注
- 168 浏览
添加回答
举报