dougou6727 2017-11-05 12:36
浏览 59
已采纳

以值的降序遍历地图(Golang)

I'm trying to traverse a map in decreasing order of the values stored against keys. I've tried :

func frequencySort(s string) string {
  var frequency map[string]int
  chararray := strings.Split(s , "")
  var a []int
  var arranged map[int]string
  for k , v := range frequency {
      arranged[v] = k
  }
  for k := range arranged {
      a = append(a , k)
  }
  sort.Sort(sort.Reverse(sort.IntSlice{a}))
}

Let's say the Map structure is :

    "a" : 9
    "b" : 7
    "c" : 19
    "d" : 11

and I'm trying to traverse it such that the output is :

"c" : 19
"d" : 11
"a" : 9
"b" : 7
  • 写回答

2条回答 默认 最新

  • dongxiezhi0590 2017-11-05 13:35
    关注

    The two map approach you have in your example will break as soon as you have more than one key in frequency with the same value, say "a":7 and "b":7, then you would lose data in arranged since keys have to be unique.

    To avoid this you could create a helper type that will hold the map's contents temporarily, just for sorting purposes. Something like this:

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    var m = map[string]int{
        "a": 9,
        "b": 7,
        "c": 19,
        "d": 11,
    }
    
    type entry  struct {
        val int
        key string
    }
    
    type entries []entry
    
    func (s entries) Len() int { return len(s) }
    func (s entries) Less(i, j int) bool { return s[i].val < s[j].val }
    func (s entries) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
    
    func main() {
        var es entries
        for k, v := range m {
            es = append(es, entry{val: v, key: k})
        }
    
        sort.Sort(sort.Reverse(es))
    
        for _, e := range es {
            fmt.Printf("%q : %d
    ", e.key, e.val)   
        }
    }
    

    https://play.golang.org/p/TPb0zNCtXO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line