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

Moh*_*med 4 c# arrays performance indexof coding-efficiency

这里是方法接收两个数组作为参数,得分数组(按降序排列),其中包含重复值,我删除了副本并将其存储在一个没有重复的新数组中,第二个数组包含特殊的玩家分数.

我需要在她的阵列中的每个分数中评估她在分数数组中的排名.我可以使用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();

}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 6

我可以用for循环来做,但它需要很长时间

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);
}
Run Code Online (Sandbox Code Playgroud)