我试图计算我的一个编码挑战的给定分数的排名,但我对收到的输出感到有点震惊。
我必须为给定的分数创建排行榜(假设分数按排序顺序位于 array
中)。我已经创建了一个方法来给出给定分数的排名,
private static int[] assignCurrentRanks(int[] scores) {
int[] currentRanks=new int[scores.length];
currentRanks[0]=1;//by default the first score will be rank 1
for(int i=1;i<currentRanks.length;i++) {
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:++currentRanks[i-1];
System.out.println("Inside the loop : ["+i+"] "+scores[i]+" "+currentRanks[i]);
}
return currentRanks;
}
示例输入:100,100,50,40,40,20,10
预期排名:1、1、2、3、3、4、5
我可以看到循环期间已正确分配等级,当我在 main 方法中打印等级后返回的数组不同时。
我知道逻辑有问题,但我找不到。请帮忙解决这个问题!!
下面是我的main
方法,
public static void main(String[] args) {
int[] scores=new int[]{100,100,50,40,40,20,10};
int[] currentRanks=assignCurrentRanks(scores);
System.out.println("Printing after the loop");
for(int i=0;i<scores.length;i++)
System.out.println("["+i+"]"+scores[i]+" "+currentRanks[i]);
}
我得到的结果是,
//index 0 is already assigned with 1 by default
Inside the loop : [1] 100 1
Inside the loop : [2] 50 2
Inside the loop : [3] 40 3
Inside the loop : [4] 40 3
Inside the loop : [5] 20 4
Inside the loop : [6] 10 5
Printing after the loop
[0]100 1
[1]100 2
[2]50 3
[3]40 3
[4]40 4
[5]20 5
[6]10 5
最佳答案
++currentRanks[i-1];\\这增加了数组元素 i-1 的值
您增加循环内使用的先验等级,导致意外行为。应该使预期的行为变为:
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:currentRanks[i-1] + 1;
关于java - 密集排名 - 使用 for 循环循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51710890/