c#Array.IndexOf(Array,item)如果没有匹配

时间:2018-04-26 11:38:37

标签: 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();

}

1 个答案:

答案 0 :(得分: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);
}