C#如何获取未排序数组中按值从小到大排序的所有元素索引
获取排序后元素的原索引数组解决方案
给定未排序数组:
int[] arr = {2,5,9,10,0, 4,1,5,3};
需要生成数组元素按值从小到大排序后的原索引数组。注意:你提供的期望输出result = {4, 6, 0, 8, 1, 7, 2, 3}遗漏了索引5(对应元素4),正确结果应包含9个索引值。
Java 实现方案
核心思路是创建索引数组,根据原数组元素值对索引进行排序:
import java.util.Arrays; import java.util.Comparator; public class SortIndices { public static void main(String[] args) { int[] arr = {2,5,9,10,0,4,1,5,3}; Integer[] indices = new Integer[arr.length]; // 初始化索引数组,存储原数组的所有索引 for (int i = 0; i < arr.length; i++) { indices[i] = i; } // 按原数组对应元素的值排序索引数组 Arrays.sort(indices, Comparator.comparingInt(index -> arr[index])); // 转换为int类型数组(按需选择) int[] result = Arrays.stream(indices).mapToInt(Integer::intValue).toArray(); // 输出结果 System.out.println("result = " + Arrays.toString(result)); } }
运行结果:
result = [4, 6, 0, 8, 5, 1, 7, 2, 3]
Python 实现方案
利用sorted函数的key参数指定排序依据:
arr = [2,5,9,10,0,4,1,5,3] # 生成索引列表并按原数组元素值排序 indices = sorted(range(len(arr)), key=lambda idx: arr[idx]) print(f"result = {indices}")
运行结果:
result = [4, 6, 0, 8, 5, 1, 7, 2, 3]
内容的提问来源于stack exchange,提问作者Muhammad Baba Goni
相关产品推荐
相关产品推荐

