c#Array.IndexOf(Array,item)如果没有匹配项,则需要最近的项目
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#Array.IndexOf(Array,item)如果没有匹配项,则需要最近的项目,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1455字,纯文字阅读大概需要3分钟。
内容图文
![c#Array.IndexOf(Array,item)如果没有匹配项,则需要最近的项目](/upload/InfoBanner/zyjiaocheng/820/0699ee1e791944d982c5d3dda9ee1e7d.jpg)
这是方法接收两个数组作为参数,
得分数组(按降序排列.)包含重复值,我删除了副本和
将它存储在一个没有重复的新数组中,
第二阵列包含特殊球员得分.
我需要在得分数组中评估她的排名
她阵中的每一个得分.
我可以使用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);
}
内容总结
以上是互联网集市为您收集整理的c#Array.IndexOf(Array,item)如果没有匹配项,则需要最近的项目全部内容,希望文章能够帮你解决c#Array.IndexOf(Array,item)如果没有匹配项,则需要最近的项目所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。