gpt4 book ai didi

Java - 获取一个int数组的升序索引

转载 作者:行者123 更新时间:2023-11-30 07:44:42 25 4
gpt4 key购买 nike

我有一个 int 数组 [2,4,1,0,0,3] 并且需要从中获取一个按升序排列的索引数组,意思是 [3,4,2,0,5,1 ].

我尝试通过使用排序数组按顺序获取数字来解决此问题,然后迭代原始数组以在匹配发生时查找索引。如下:

public class IndexAscendingSorter {
public static void main (String[] args) {
int[] array = {2,4,1,0,0,3};
IndexAscendingSorter finder = new IndexAscendingSorter();
int[] indixes = finder.orderIndexAscending(array);

System.out.println("Indexes of the array in ascending order: " +
Arrays.toString(indixes));
}

public int[] orderIndexAscending(int[] array) {
int[] minimumIndexes = new int[array.length];
int[] sortedArray = array.clone();
Arrays.sort(sortedArray);

for (int index = 0; index < array.length; index++){
int minIndex = 0;
for (int number : array) {
if (number == sortedArray[index]) {
minimumIndexes[index] = minIndex;
break;
}
minIndex++;
}
}
return minimumIndexes;
}
}

问题是对于相同的数字不返回正确的索引,执行该代码的输出是:

Indexes of the array in ascending order: [3, 3, 2, 0, 5, 1] The second value array[1] should have been 4 instead of 3. Does anyone know how can I improve this?

最佳答案

继续您的方法,一个快速的解决方案是使用哈希集,您将在其中添加您已经使用的索引,然后可以检查它是否是重复索引。只需将 orderIndexAscending() 函数更改为:

    public int[] orderIndexAscending(int[] array) {
int[] minimumIndexes = new int[array.length];
int[] sortedArray = array.clone();
Arrays.sort(sortedArray);
Set<Integer> savedIndexes = new HashSet<>();

for (int index = 0; index < array.length; index++){
int minIndex = 0;
// Add the index in ascending order, we need to keep the indexes already
// saved, so won't miss indexes from repeted values
for (int number : array) {
if (number == sortedArray[index] && !savedIndexes.contains(minIndex)) {
savedIndexes.add(minIndex);
minimumIndexes[index] = minIndex;
break;
}
minIndex++;
}
}
return minimumIndexes;
}
}

关于Java - 获取一个int数组的升序索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360489/

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