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

标签 c# arrays performance indexof coding-efficiency

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

我需要评估她在 scores 数组中的排名 她数组中的每个分数。 我可以用 for 循环来完成,但这需要很长时间,我尝试使用数组 .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);
}

关于c# Array.IndexOf(Array,item) 如果没有匹配则需要最接近的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50042025/

相关文章:

performance - 快速查询在 SSRS 中运行缓慢

performance - 提高 Quartz2D 绘图性能

c# - iOS 中的重复性后台任务

c# Uri 加载不确定?

c - 在C中迭代结束时打印出迭代数组

arrays - 如何在 Perl 中正确替换哈希数组中的值?

iphone - iOS 中检查字符串是否是字符串列表之一的最有效方法是什么?

c# - 带有按钮 onClick 事件的 UserControl 的事件处理程序

c# - .NET Core 2 和 DI - 在构造函数中使用 appsettings.json 中的值?

java - 抽象类错误 : Exception in thread "main" java. lang.NullPointerException