AlgoExpert 问题,锦标赛获胜者,未通过所有测试用例

AlgoExpert Question, Tournament Winner, Not passing all test cases

锦标赛获胜者:正在举行算法锦标赛,程序员团队相互竞争,以尽可能快的速度解决算法问题。团队在循环赛中竞争,每个团队都与所有其他团队对决。一次只有两支队伍相互竞争。 (附加的屏幕截图中的其余问题)。

我的代码只通过了 6/10 个测试用例。我知道我的“bestTeam”没有更新,但我不确定为什么。请帮我找出我哪里出错了。

测试用例失败:

输入:

{
  "competitions": [
    ["HTML", "C#"],
    ["C#", "Python"],
    ["Python", "HTML"]
  ],
  "results": [0, 0, 1]
}

我的结果是“C#”,而它应该是“Python”

class Program {

  public String tournamentWinner(
      ArrayList<ArrayList<String>> competitions, ArrayList<Integer> results) {
    
        Hashtable<String, Integer> tableTeamNameAndPoints = new Hashtable<>();
        String bestTeam = "";

        tableTeamNameAndPoints.put(bestTeam, 0);

        for(int i = 0; i < competitions.size(); i++){
          String winningTeamName = results.get(i) == 0 ? 
            competitions.get(i).get(1) : competitions.get(i).get(0);

          if(!tableTeamNameAndPoints.contains(winningTeamName)){
            tableTeamNameAndPoints.put(winningTeamName, 3);          
        }
          if(tableTeamNameAndPoints.contains(winningTeamName)){
            Integer updatedScore = tableTeamNameAndPoints.get(winningTeamName) + 3;
            tableTeamNameAndPoints.put(winningTeamName, updatedScore);          
          }

        if (tableTeamNameAndPoints.get(winningTeamName) > tableTeamNameAndPoints.get(bestTeam)){
            bestTeam = winningTeamName;
          }
      }
        
        return bestTeam;
  }
}

您应该在这一行使用 containsKey on your Hashtable instead of contains

if (!tableTeamNameAndPoints.contains(winningTeamName)) {

当您使用 contains, you're checking if the Hashtable contains a key that maps to the value provided. It's equivalent to the containsValue 方法时。

您还可以删除不需要的第二个 if 语句(条件始终为 true)并且具有相同的 contains 问题:

if (tableTeamNameAndPoints.contains(winningTeamName)) {