繁体   English   中英

将数组传递给委托方法作为ref

[英]Passing array to delegate method as ref

我试图解决这个 HackerRank挑战,并在此处发布了@DNKpp的C ++算法。 这是一个有效的C#版本:

class Demo
{
    delegate int MyDelegate(int[] _scores, int _aScore);

    static int[] climbingLeaderboard(int[] scores, int[] alice)
    {
        int[] result = new int[alice.Count()];

        var distinctScores = scores.Distinct().ToArray();

        MyDelegate locateRanking = (scoresArr, aliceScore) => {
            var itr = Array.Find(scoresArr, el => el <= aliceScore);
            var idx = Array.FindIndex(scoresArr, score => score == itr);
            return idx == -1 ? distinctScores.Count() + 1 : idx + 1;
        };

        for (int i = 0; i < alice.Count(); i++)
        {
            result[i] = locateRanking(distinctScores, alice[i]);
        }
        return result;
    }



    static void Main(string[] args)
    {
        int[] scores = { 100, 90, 90, 80, 75, 60 };
        int[] alice = { 50, 65, 77, 90, 102 };
        int[] result = new int[alice.Count()];

        result = climbingLeaderboard(scores, alice);
    }
}

climbingLeaderboard功能签名是固定的。
但是我想将scores作为对locateRankingref 可能吗? 我遇到错误了。 此外,此C#版本在HackerRank上已超时。 我该如何改善?

你有尝试过吗? (我在委托和函数中添加了ref关键字):

class Demo
{
    delegate int MyDelegate(ref int[] _scores, int _aScore);

    static int[] climbingLeaderboard(int[] scores, int[] alice)
    {
        int[] result = new int[alice.Count()];

        var distinctScores = scores.Distinct().ToArray();

        MyDelegate locateRanking = (ref int[] scoresArr, int aliceScore) => {
            var itr = Array.Find(scoresArr, el => el <= aliceScore);
            var idx = Array.FindIndex(scoresArr, score => score == itr);
            return idx == -1 ? distinctScores.Count() + 1 : idx + 1;
        };

        for (int i = 0; i < alice.Count(); i++)
        {
            result[i] = locateRanking(ref distinctScores, alice[i]);
        }
        return result;
    }



    static void Main(string[] args)
    {
        int[] scores = { 100, 90, 90, 80, 75, 60 };
        int[] alice = { 50, 65, 77, 90, 102 };
        int[] result = new int[alice.Count()];

        result = climbingLeaderboard(scores, alice);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM