[英]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
作為對locateRanking
的ref
。 可能嗎? 我遇到錯誤了。 此外,此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.