【问题标题】:List ranking algorithm [duplicate]列表排名算法[重复]
【发布时间】:2010-09-22 22:33:21
【问题描述】:

给定一个数字列表,可以是任意顺序,比如

3, -5, -1, 2, 7, 12, -8

我想生成一个代表他们排名的列表,在这种情况下是

4, 1, 2, 3, 5, 6, 0

这些数字实际上是有序列表中的某个成员。请注意,列表的顺序不会改变,它们只是根据排名进行计数。

(这些数字代表 z 顺序,但可能还有其他用途)

【问题讨论】:

  • 我认为this 是同一个问题
  • 什么对你很重要?时间(我们可以排序并设置一个哈希)?

标签: algorithm sorting ranking


【解决方案1】:

这是我的解决方案,尚未经过测试:

// this will be our storage of the new z-order
int *tmpZ = new int[GetCount()];

int currentZ = INT_MIN;
int smallestIdx = -1;
int newZ = 0;
for (int passes = 0; passes < GetCount(); passes++)
{
    int smallestZ = INT_MAX;
    // find the index of the next smallest item
    for (int i = 0; i < GetCount(); i++)
    {
        if (GetAt(i)->m_zOrder > currentZ && GetAt(i) < smallestZ)
        {
            smallestIdx = i;
            smallestZ = GetAt(i)->m_zOrder;
        }
    }
    tmpZ[smallestIdx] = newZ;

    // prepare for the next item
    currentZ = smallestZ;
    newZ++;
    smallestIdx = -1;
}

// push the new z-order into the array
for (int i = 0; i < GetCount(); i++)
    GetAt(i)->m_zOrder = tmpZ[i];

如你所见,它是 O(n^2).... :(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2020-05-11
    • 2019-06-25
    • 2012-09-14
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多