加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:04:09 所属栏目:大数据 来源:网络整理
导读:我知道我们可以使用 sort.Sort(sort.Reverse(sort.IntSlice(example))) 排序数组. 但是我如何获得数组的索引? 例如 example := []int{1,25,3,5,4} 我想得到输出:1,4,2 为sort.IntSlice创建一个包装器,它会记住索引并在交换值时交换它们: type Slice struc
我知道我们可以使用
sort.Sort(sort.Reverse(sort.IntSlice(example)))

排序数组.

但是我如何获得数组的索引?

例如

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

我想得到输出:1,4,2

为sort.IntSlice创建一个包装器,它会记住索引并在交换值时交换它们:
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]
}

游乐场:http://play.golang.org/p/LnSLfe-fXk.

编辑:正如DaveC在评论中提到的,您实际上可以使用sort.Interface来为任何可排序类型创建数据结构:

type Slice struct {
    sort.Interface
    idx []int
}

func (s Slice) Swap(i,j int) {
    s.Interface.Swap(i,s.idx[i]
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读