获得一个无序的双数组索引排序后 [英] Getting the indices of an unsorted double array after sorting
问题描述
这个问题来为这个伴侣<一个href=\"http://stackoverflow.com/questions/25802052/getting-the-largest-k-elements-of-a-double-array\">one这算是最快的排序双阵列。
This question comes as a companion of this one that regarded fastest sorting of a double array.
现在我想要得到的顶部 - K对应的排序的数组
指数
Now I want to get the top-k
indices corresponding to the unsorted array.
我已经实现了这个版本,它(不幸)使用自动装箱和的HashMap
在一些答案,包括这个的 之一:
I have implemented this version which (unfortunately) uses autoboxing and HashMap
as proposed in some answers including this one:
HashMap<Double, Integer> map = new HashMap<Double, Integer>();
for(int i = 0; i < numClusters; i++) {
map.put(scores[i], i);
}
Arrays.sort(scores);
HashSet<Integer> topPossibleClusters = new HashSet<Integer>();
for(int i = 0; i < numClusters; i++) {
topPossibleClusters.add(map.get(scores[numClusters - (i+1)]));
}
正如你可以看到这个使用了的HashMap
的钥匙原始数组,并作为双击
值的值的原数组的索引。
因此,整理原始数组后,我刚刚从<$ C $ C>地图检索。
As you can see this uses a HashMap
with keys the Double
values of the original array and as values the indices of the original array.
So, after sorting the original array I just retrieve it from the map
.
我也用 HashSet的
,因为我很感兴趣,决定是否在 INT
包含在这一套,使用。载有()
方法。 (我不知道这使得因为我在其他问题中提到的差异我的数组是小-50元素 - )。如果这不会有所作为点出来,虽然。
I also use HashSet
as I am interested in deciding if an int
is included in this set, using .contains()
method. (I don't know if this makes a difference since as I mentioned in the other question my arrays are small -50 elements-). If this does not make a difference point it out though.
我不感兴趣的价值本身,只有指数。
I am not interested in the value per se, only the indices.
我的问题是,是否有一个更快的方法去用它?
My question is whether there is a faster approach to go with it?
推荐答案
这有点互连的/联锁集合适合于脆弱,易断,难以调试,难以维护code。
This sort of interlinking/interlocking collections lends itself to fragile, easily broken, hard to debug, unmaintainable code.
而不是创建一个对象:
class Data {
double value;
int originalIndex;
}
创建数据对象存储原始值和索引数组
Create an array of Data objects storing the original value and index.
使用自定义的比较,着眼于data.value和排序降序排序它们。
Sort them using a custom comparator that looks at data.value and sorts descending.
现在您的数组中的顶的X项目是你想要的,你可以只是看看值
和 originalIndex
,你需要他们。
Now the top X items in your array are the ones you want and you can just look at the value
and originalIndex
as you need them.
这篇关于获得一个无序的双数组索引排序后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!