c# Array.IndexOf(Array,item) 如果没有匹配则需要最接近的项目

c# Array.IndexOf(Array,item) need the closest item if there is no match

这是接收两个数组作为参数的方法, 包含重复值的分数数组(按降序排列。),我删除了重复项和 将它存储在一个新数组中而不重复, 第二个数组包含特殊玩家分数。

我需要评估她在 scores 数组中的排名 她数组中的每个分数。 我可以用 for 循环来做,但这需要很长时间,我尝试使用 Array .IndexOf 方法,但对于不存在的值我得到了 -1。

代码:

static int[] climbingLeaderboard(int[] scores, int[] alice)
{
    var aliceRecord = new List<int>();
    int[] oneArray;
    oneArray = scores.Distinct().ToArray();
    foreach (var aliceScore in alice)
    {
        if (aliceScore < oneArray[oneArray.Length - 1])
        {
            aliceRecord.Add(oneArray.Length + 1);
        }
        else
        {
            var rank = Array.IndexOf(oneArray, aliceScore);
            if (rank < 0)
            {
              //Here I need the help
              //I comented the un efficient code
               //for (int i = 0; i < oneArray.Length; i++)
               //{
               //    if (aliceScore >= oneArray[i])
               //    {
               //        aliceRecord.Add(i + 1);
               //        break;
               //    }
               //
               //
               //}
            }
            else
            {
                aliceRecord.Add(rank + 1);
            }
        }
    }
    return aliceRecord.ToArray();

}

I could do it with for loop, but it requires long time

Array.IndexOf 是一个 O(n) 操作,因此与 运行 循环相比,您不会有太大改进。

排序 oneArray 会打开一个更快的方法 - 使用二进制搜索:

var oneArray = scores.Distinct().OrderBy(s=>s).ToArray();
foreach (var aliceScore in alice) {
    int pos = Array.BinarySearch(oneArray, aliceScore);
    if (pos < 0) {
        // When the index is negative, it represents the bitwise
        // complement of the next larger score:
        pos = ~pos - 1;
    }
    // Array is ordered in ascending order, so you want the index
    // counting from the back
    aliceRecord.Add(oneArray.Length - pos);
}