簡體   English   中英

在小於 O(n^2) 的范圍內對給定的整數列表進行排名

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM