【问题标题】:Ranking a given list of integers in less than O(n^2)在小于 O(n^2) 的范围内对给定的整数列表进行排名
【发布时间】:2015-06-12 12:05:39
【问题描述】:

如何为给定整数列表中的元素分配等级? 有没有时间复杂度小于 O(n^2) 的算法?

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

【问题讨论】:

  • 对它们进行排名是什么意思?标准化?

标签: java arrays algorithm time-complexity


【解决方案1】:

您可以在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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多