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条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案