doubi3996 2018-03-01 20:21
浏览 41
已采纳

在Golang中使用地图

I am new to Go and doing a few exercises. One of them is to sort the numbers in an array by frequency, from most to least frequent.

Example: 
Input: [2, 2, 5, 7, 4, 4, 4, 7, 2]
Output: [2, 4, 7, 5]

Note that [4, 2, 7, 5] would also be correct, since 4 and 2 have the same frequency.

For this purpose I am converting the array into a value value map, which here would look like this: [2:3][4:3][7:2][5:1] (2 and 3 have freq. of 3, 7 has the freq of 2,... )

Afterwards I would like to simply loop through the map and output the keys ordered by value. For that I use the following code, which apparently does not work. Why?

count := 0
max := -1

// break loop, if map is empty
for i := 0; i < 1; i-- {
    if len(m) == 0 {
        break
    }

    max = -1

    // get key of biggest value
    for k, v := range m {
        if v > max {
            max = k
        }
    }
    // res (for result) is a slice of integers
    res[count] = max
    // remove key-value-pair from map
    delete(m, max)
    count++
}
return res

Please keep in mind that this is an exercise. I am very sure there are much better, build in ways to do this.

  • 写回答

2条回答 默认 最新

  • dongyi7041 2018-03-01 21:36
    关注

    Your 'max' variable is meant to keep track of the maximum frequency seen so far. However when you do 'max = k' you're assigning a key.

    You need to keep track of the maximum frequency and the key associated with that frequency in separate variables.

    ...
    for k, v := range m {
        if v > maxFreq {
            maxFreq = v
            mostFrequentKey = k
        }
    }
    // res (for result) is a slice of integers
    res[count] = mostFrequentKey
    // remove key-value-pair from map
    delete(m, mostFrequentKey)
    count++
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来