更新时间:2023-12-03 17:19:10
尝试对按值比较的 (value, index)
对进行排序:
Try sorting pairs of (value, index)
compared by value:
public class Pair implements Comparable<Pair> {
public final int index;
public final int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
//multiplied to -1 as the author need descending sort order
return -1 * Integer.valueOf(this.value).compareTo(other.value);
}
}
然后,当您要排序时:
public static void main(String[] args) {
Pair[] yourArray = new Pair[10];
//fill the array
yourArray[0] = new Pair(0, 5); yourArray[1] = new Pair(1, 10); //and so on
Arrays.sort(yourArray);
}
现在,您有一个 Pair
对象数组,按 value
降序排列.每个对象还包含 index
- 在原始数组中的位置.
Now, you have an array of Pair
object ordered by value
descending. Each object also contains index
- the place in the original array.
P.S. 我用 Java 编写了示例,因为问题具有 java
标记.虽然在C++
中思路是一样的,只是实现上有点不同.
P. S. I wrote the sample in Java as the question has java
tag. Although, in C++
the idea is the same, only the implementation is a little bit different.