Java在一个新数组中对索引进行排序

huangapple go评论59阅读模式
英文:

Java sorting indices in a new array

问题

Here's the translation of the provided content:

假设我有一个数组 test-

int[] test={5,4,3,2,1};

现在,当我按升序对这个数组进行排序时,我想将元素的索引存储在一个新数组中。因此,对上述数组按升序排序应该创建一个新数组,其值为 {4,3,2,1,0}。
在 C++ 中,代码如下:

vector<int> order(n);
iota(order.begin(),order.end(),0);
sort(order.begin(),order.end(),[&](int i,int j){
     return test[i]<=test[j];
});

我想知道如何在 Java 中使用比较器类实现这一点。

英文:

Suppose I have an array test-

int[] test={5,4,3,2,1};

Now when I sort this array in increasing order I want to store the indices of the elements in a new array. So sorting the above array in increasing order should create a new array with values {4,3,2,1,0}
In C++ this is the code--

vector&lt;int&gt; order(n);
iota(order.begin(),order.end(),0);
sort(order.begin(),order.end(),[&amp;](int i,int j){
     return test[i]&lt;=test[j];
});

I wanted to know how I can implement this in Java using the comparator class

答案1

得分: 1

你可以使用Comparator.comparing来根据索引的值对所有索引进行排序,方法如下:

int[] res = IntStream.range(0, test.length)
                     .boxed()
                     .sorted(Comparator.comparing(e -> test[e]))
                     .mapToInt(e -> e)
                     .toArray();

输出结果:[4, 3, 2, 1, 0]

英文:

You can sort all the index by that index's value using Comparator.comparing this way

int[] res = IntStream.range(0, test.length)
                     .boxed()
                     .sorted(Comparator.comparing(e -&gt; test[e]))
                     .mapToInt(e -&gt; e)
                     .toArray();

Output: [4, 3, 2, 1, 0]

huangapple
  • 本文由 发表于 2020年10月1日 01:38:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64142954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定