本文介绍了获取数组中n个最小元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个int数组 int [] myArray = new int [100];
,想要获取最小10个(任何n个)元素的索引.我该怎么办?
I have an int array int[] myArray = new int[100];
and want to get indexes of smallest 10 (any n) elements. How can I do this?
推荐答案
创建一个包含数字和索引的对象,然后创建这些对象的数组,然后执行Array.Sort(arrayset [],比较器) java docs .然后,您可以从排序后的数组中挑选出前x个项.
make an object that contains the number and the index, then make an array of these objects, then perform Array.Sort(arrayset[], comparator) java docs. Then you can just pick out the top x items from the sorted array.
像这样... [我曾经用它来根据'距离'进行排序
Something like this... [I had used this to sort according to 'distance'
import java.util.Arrays;
import java.util.Comparator;
public class NearestObject
{
public NearestObject(int position, int distance)
{
this.Position = position;
this.Distance = distance;
}
public int Position = 0;
public int Distance = 0;
public static NearestObject[] SortDistance(NearestObject[] items)
{
Arrays.sort(items, new DistanceSort());
return items;
}
}
class DistanceSort implements Comparator<NearestObject>
{
public int compare(NearestObject o1, NearestObject o2)
{
return o1.Distance - o2.Distance;
}
}
这篇关于获取数组中n个最小元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!