[英]Java - Obtain the indexes in ascending order of an int array
我有一个[2,4,1,0,0,3]的int数组,需要从中获取升序的索引数组,表示[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;
}
}
问题在于,对于相同的数字不会返回正确的索引,执行该代码的输出为:
数组的索引以升序排列:[3、3、2、0、5、1]第二个值array [1]应该是4而不是3。有人知道如何改善这一点吗?
继续您的方法,一种快速的解决方案是使用哈希集,在其中您将添加已经使用的索引,然后可以检查它是否是重复索引。 只需将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;
}
}
将数字与原始索引配对:
[2,4,1,0,0,3] => [[2,0],[4,1],[1,2],[0,3],[0,4],[3,5]]]
然后按原始值排序:
=> [[0,3],[0,4],[1,2],[2,0],[3,5],[4,1]]]
最后提取索引:
=> [3,4,2,0,5,1]
将索引数组初始化为Integers
0、1、2、3,...,然后使用自定义编译器对索引数组进行排序,该自定义编译器查找相应的数组值并进行比较。
for (int index = 0; index < array.length; index++){
int minIndex = 0;
for (int number : array) {
if (number == sortedArray[index]) {
minimumIndexes[index] = minIndex;
array[minIndex]=Integer.MAX_VALUE;
break;
}
minIndex++;
}
}
您可以简单地使用数组中从未存在的任何值来更新已访问的值。
您可以简单地使用数组中不存在的任何值来更新已经访问过的值。
for (int index = 0; index < array.length; index++){
int minIndex = 0;
for (int number : array) {
if (number == sortedArray[index]) {
minimumIndexes[index] = minIndex;
array[minIndex]=Integer.MAX_VALUE;
break;
}
minIndex++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.