doubao7287 2015-06-30 14:34
浏览 503
已采纳

在golang中排序后获取数组的索引

I know we can use

sort.Sort(sort.Reverse(sort.IntSlice(example)))

to sort a array.

But how can I get the indices of the array?

e.g.

example := []int{1, 25, 3, 5, 4}

I want to get the output: 1, 3, 5, 4, 2

  • 写回答

1条回答 默认 最新

  • drsh30452 2015-06-30 14:47
    关注

    Make a wrapper for sort.IntSlice that remembers the indexes and swaps them when it swaps the values:

    type Slice struct {
        sort.IntSlice
        idx []int
    }
    
    func (s Slice) Swap(i, j int) {
        s.IntSlice.Swap(i, j)
        s.idx[i], s.idx[j] = s.idx[j], s.idx[i]
    }
    

    Playground: http://play.golang.org/p/LnSLfe-fXk.

    EDIT: As DaveC mentioned in the comments, you can actually wrap around sort.Interface to create a data structure for any sortable type:

    type Slice struct {
        sort.Interface
        idx []int
    }
    
    func (s Slice) Swap(i, j int) {
        s.Interface.Swap(i, j)
        s.idx[i], s.idx[j] = s.idx[j], s.idx[i]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services