【发布时间】:2020-04-28 12:45:38
【问题描述】:
Alice 正在玩一款街机游戏,她想爬到排行榜的顶端,并想跟踪她的排名。游戏使用密集排名,所以它的排行榜是这样工作的:
1:得分最高的玩家在排行榜上排名第一。 2:得分相同的玩家获得相同的排名号,下一位玩家获得紧随其后的排名号。
例如,排行榜上的四位玩家得分分别为 100、90、90 和 80。这些玩家的排名分别为 1、2、2 和 3。如果 Alice 的分数是 70、80 和 105,那么她在每场比赛后的排名分别是第 4、第 3 和第 1。
我已经尝试过这段代码,它可以正确处理 100000 个输入,但是在处理 200000 个输入时它会超时。
int* climbingLeaderboard(int scores_count, int* scores, int alice_count, int* alice, int* result_count)
{
//here scores array is sorted in descending order
//and alice array is sorted in ascending order
int rank[scores_count];
int i, j, temp;
//inserting rank in rank array according to the scores of scores array
rank[0] = 1;
temp = scores[0];
for(i=1;i<scores_count;i++)
{
if(scores[i] == temp)
rank[i] = rank[i-1];
else
{
rank[i] = rank[i-1] + 1;
temp = scores[i];
}
}
//Now finding the rank of alice's scores and
//reusing the alice array to store the required rank
for(j=0;j<alice_count;j++)
{
//case 1: if alice's score is the lower
//than the lowest score of scores array
if(alice[j] < scores[scores_count-1])
alice[j] = rank[scores_count-1] + 1;
//case 2: if alice's score is greater
//than the highest score pf the scores array
else if(alice[j] > scores[0])
alice[j] = 1;
//case 3: when alice's score is in between the max-min range
else
{
for(i=0;i<scores_count;i++)
{
if((alice[j] > scores[i]) || (alice[j]) == scores[i])
{
alice[j] = rank[i];
scores_count = i;
break;
}
}
}
}
*result_count = alice_count;
return alice;
}
【问题讨论】:
-
不要使用
for(i=0;i<scores_count;i++) { if((alice[j] > scores[i]) || (alice[j]) == scores[i])...进行线性搜索,而是使用二分搜索(因为scores[]已排序)。也可能是排序后的scores[]的未发布形式效率低下。
标签: c optimization timing