我必须根据相同位置的值对数组进行排名。例如:
值 = {5, 1, 4 }
生成的排名数组将为:{1, 3 ,2}
如何在不对数组进行排序的情况下实现此目的?
你应该写这样的东西:
public static int[] getRanksArray(int[] array) {
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] > array[i]) {
count++;
}
}
result[i] = count + 1;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
此方法返回具有等级的数组,其索引对应于输入数组中的值索引(如果值相等,则它们共享一个公共等级)
你不能使用排序,所以我没有看到任何方法来避免O(NxN)渐近复杂度和O(N)辅助空间:(
| 归档时间: |
|
| 查看次数: |
5802 次 |
| 最近记录: |