简体   繁体   中英

Ranking a given list of integers in less than O(n^2)

How to assign ranks to elements in a given list of integers? Is there an algorithm for that with time complexity less than O(n^2) ?

Input:  2 6 7 3 9
Output: 1 3 4 2 5

You can easily do this in O(n * log n) by sorting:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM