【问题标题】:c# Array.IndexOf(Array,item) need the closest item if there is no matchc# Array.IndexOf(Array,item) 如果没有匹配则需要最近的项目
【发布时间】:2018-10-07 02:18:55
【问题描述】:

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

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

}

【问题讨论】:

  • alice数组没有排序?
  • 不,不是,出于问题(问题)的目的,我无法对其进行排序,因为我需要根据她的分数记录她的历史记录

标签: c# arrays performance indexof coding-efficiency


【解决方案1】:

我可以用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);
}

【讨论】:

  • 抱歉,不起作用,使用此示例输入 oneArray{100 , 50 , 40 , 20 , 10} AliceScores{5 , 25 , 50 , 120} 您的代码输出 6 , 0 , 5 , 5 My代码输出 6 , 4 , 2 , 1
  • 对不起,我只是在编辑评论,如果你想看的话,这里是问题链接和来自hackerrank的解释hackerrank.com/challenges/climbing-the-leaderboard/problem
  • @Mohamed 那是因为数组是按升序排列的二分查找,所以要推送oneArray.Length - pos。查看编辑,它通过了hackerrank的所有测试。
  • OMG,你真是个天才,我花了 6 个小时才写出低效的解决方案,甚至我的 c# 课程中的老师 Run Away 告诉我,我们明天可能有更多时间。你能建议一些学习方法来提高我的知识吗,我正在看复数课程,但它并没有提高,谢谢你的时间
  • @Mohamed 我无法推荐一个学习这个的好网站——我从大约 30 多年前的一本过时的书里学到了东西,然后编程了 30 多年。改进编码的一种方法是解决很多hackerrank.com 和topcoder.com 问题,它们涵盖了很多编程技巧。
猜你喜欢
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多