gpt4 book ai didi

java - 如何打印数组中 10 个最小值的索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:38 25 4
gpt4 key购买 nike

我需要从数组(2000 项)中选择 10 个最小的数字并打印它们的索引。

起初我尝试只对这个数组进行排序并打印值数组 [0 到 9]。这是最小的数字,但我丢失了这个值的索引,他们有一个未排序的数组。

第二个选项尝试使用 treeMap 效果很好,但是当我有两个相同的键时它只打印其中一个,但我需要打印它们两个。

treeMap 使用代码示例:

  TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

treemap.put(2, "two");
treemap.put(1, "one");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(6, "six2");
treemap.put(5, "five");

Collection<String> coll=treemap.values();
System.out.println("Value of the collection: "+coll);

直到现在我还没有使用 treeMap,所以有可能存在一些简单的方法来修复它。还是使用其他东西更好?

如有任何帮助,我将不胜感激

最佳答案

It was the smallest numbers but I lost indexes of this values, which they had i non-sorted array

那你为什么不创建一个类来保存这个索引呢?然后只需按值对数组进行排序,您就会得到关联的索引。

class MyClass implements Comparable<MyClass>{
private int index;
private int value;

public MyClass(int i, int v){
this.index = i;
this.value = v;
}

@Override
public String toString(){
return "Index: "+index+" Value: "+value;
}

@Override
public int compareTo(MyClass m) {
return value - m.value;
}
}

public static void main(String[] args){   
MyClass[] array = new MyClass[20];

for(int i = 0; i < array.length; i++){
array[i] = new MyClass(i, someRandomValue); // Here I used (i*3 + 2)%5
}
System.out.println(Arrays.toString(array));
Arrays.sort(array);
MyClass [] arraySorted = Arrays.copyOfRange(array, 0, 10); //take the first ten elements
System.out.println(Arrays.toString(arraySorted));
}


注意:

如果你想按索引对具有相同值的对象进行排序,你可以像这样修改你的比较器:

@Override
public int compareTo(MyClass m) {
int compareValue = value - m.value;
if(compareValue == 0)
return index - m.index;
return compareValue;
}


输出(使用第二个 compareTo 方法):

Before :
[Index: 0 Value: 2, Index: 1 Value: 0, Index: 2 Value: 3, Index: 3 Value: 1, Index: 4 Value: 4, Index: 5 Value: 2, Index: 6 Value: 0, Index: 7 Value: 3, Index: 8 Value: 1, Index: 9 Value: 4, Index: 10 Value: 2, Index: 11 Value: 0, Index: 12 Value: 3, Index: 13 Value: 1, Index: 14 Value: 4]

After :
[Index: 1 Value: 0, Index: 6 Value: 0, Index: 11 Value: 0, Index: 3 Value: 1, Index: 8 Value: 1, Index: 13 Value: 1, Index: 0 Value: 2, Index: 5 Value: 2, Index: 10 Value: 2, Index: 2 Value: 3]

关于java - 如何打印数组中 10 个最小值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com