簡體   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