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 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下