我试图解决this的HackerRank挑战,并发现了@DNKpp发布的here的C ++算法。 这是一个有效的C#版本:
(double)charLen
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
传递到ref
中。可能吗?我遇到错误了。此外,此C#版本在HackerRank上已超时。我该如何改善?
答案 0 :(得分:3)
您尝试过吗? (我已经在委托和函数中添加了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);
}
}