LeetCode 3322: Premier League Table Ranking III
Problem Description
Explanation
To solve this problem, we can use a data structure like a hashmap to store the team names as keys and their corresponding scores as values. We can then sort the hashmap entries based on the scores to get the final ranking of the teams. If two teams have the same score, we can compare their names in lexicographical order to determine the ranking.
Algorithm:
- Create a hashmap to store team names and their scores.
- Iterate over the matches and update the scores of the corresponding teams based on the match results.
- Sort the hashmap entries based on scores in descending order.
- If two teams have the same score, compare their names in lexicographical order.
- Generate the final ranking based on the sorted hashmap.
Time Complexity:
- The time complexity of this approach is O(nlogn) where n is the number of teams.
Space Complexity:
- The space complexity is O(n) for storing the hashmap entries.
Solutions
import java.util.*;
class Solution {
public List<String> ranking(String[] matches) {
Map<String, Integer> scores = new HashMap<>();
for (String match : matches) {
String[] teams = match.split(",");
String team1 = teams[0];
String team2 = teams[1];
int score1 = Integer.parseInt(teams[2]);
int score2 = Integer.parseInt(teams[3]);
scores.put(team1, scores.getOrDefault(team1, 0) + (score1 > score2 ? 3 : score1 == score2 ? 1 : 0));
scores.put(team2, scores.getOrDefault(team2, 0) + (score2 > score1 ? 3 : score1 == score2 ? 1 : 0));
}
List<String> ranking = new ArrayList<>(scores.keySet());
Collections.sort(ranking, (a, b) -> {
int scoreDiff = scores.get(b) - scores.get(a);
if (scoreDiff == 0) {
return a.compareTo(b);
}
return scoreDiff;
});
return ranking;
}
}
Loading editor...