You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang如何借助标准sort包排序nums1并同步对应交换nums2元素?

用Go标准sort包实现双切片同步排序

完全可以用Go标准库的sort包实现,不用自己写排序逻辑,下面是两种实用的实现方式:

方式一:基于索引切片排序

这种方法通过对索引排序来映射原切片的元素对应关系,步骤清晰:

  • 先创建一个索引切片,存储0到切片长度-1的整数
  • 按照nums1中对应元素的大小对索引切片排序
  • 最后根据排序后的索引重新生成nums1和nums2

代码示例:

package main

import (
	"fmt"
	"sort"
)

func main() {
	nums1 := []int{1, 3, 2, 4}
	nums2 := []int{12, 47, 23, 1}

	// 初始化索引切片
	indices := make([]int, len(nums1))
	for i := range indices {
		indices[i] = i
	}

	// 按nums1的元素大小排序索引
	sort.Slice(indices, func(i, j int) bool {
		return nums1[indices[i]] < nums1[indices[j]]
	})

	// 根据排序后的索引生成新的切片
	sortedNums1 := make([]int, len(nums1))
	sortedNums2 := make([]int, len(nums2))
	for i, idx := range indices {
		sortedNums1[i] = nums1[idx]
		sortedNums2[i] = nums2[idx]
	}

	// 替换原切片(按需选择)
	nums1, nums2 = sortedNums1, sortedNums2

	fmt.Println("nums1:", nums1) // [1 2 3 4]
	fmt.Println("nums2:", nums2) // [12 23 47 1]
}

方式二:绑定元素为结构体排序

把两个切片的对应元素绑定到结构体中,直接对结构体切片排序后再拆解:

  • 定义一个包含两个字段的结构体,分别对应nums1和nums2的元素
  • 构建结构体切片,填充对应元素
  • 按结构体中nums1对应的字段排序
  • 从排序后的结构体切片中提取元素更新原切片

代码示例:

package main

import (
	"fmt"
	"sort"
)

// 定义结构体绑定两个切片的对应元素
type Pair struct {
	Val1 int
	Val2 int
}

func main() {
	nums1 := []int{1, 3, 2, 4}
	nums2 := []int{12, 47, 23, 1}

	// 填充结构体切片
	pairs := make([]Pair, len(nums1))
	for i := range pairs {
		pairs[i] = Pair{Val1: nums1[i], Val2: nums2[i]}
	}

	// 按Val1字段排序结构体切片
	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].Val1 < pairs[j].Val1
	})

	// 拆解回原切片
	for i := range nums1 {
		nums1[i] = pairs[i].Val1
		nums2[i] = pairs[i].Val2
	}

	fmt.Println("nums1:", nums1) // [1 2 3 4]
	fmt.Println("nums2:", nums2) // [12 23 47 1]
}

两种方法都只用到了Go标准库的sort包,完全符合你的需求,且能保证两个切片的元素对应关系始终同步。

内容的提问来源于stack exchange,提问作者Cecilia Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:15:20