gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:48:06 25 4
gpt4 key购买 nike

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

我需要评估她在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com