![](/img/trans.png)
[英]How to create array [1, 2, 3, 1] from given range Q queries with N elements each [1, 3] [2, 3] [3, 4] in less than O(QN)?
[英]Ranking a given list of integers in less than O(n^2)
如何为给定整数列表中的元素分配等级? 是否有时间复杂度小于 O(n^2) 的算法?
Input: 2 6 7 3 9
Output: 1 3 4 2 5
您可以通过排序在O(n * log n)
轻松完成此操作:
int[] input = //...
int[] input = new int[]{2, 6, 7, 3, 9};
Integer[] indices = new Integer[input.length];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
// find permutation of indices that would yield sorted input
Arrays.sort(indices, Comparator.comparingInt(i -> input[i]));
// invert permutation and add 1 to get rank
int[] ranks = new int[indices.length];
for (int i = 0; i < indices.length; i++) {
ranks[indices[i]] = i+1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.