from collections import defaultdict
def teamScores(matches):
scores = defaultdict(int)
for match in matches:
team1, team2, score1, score2 = match
if score1 > score2:
scores[team1] += 3
scores[team2] += 0
elif score1 < score2:
scores[team1] += 0
scores[team2] += 3
else:
scores[team1] += 1
scores[team2] += 1
return dict(scores)
#include <unordered_map>
#include <string>
#include <vector>
using namespace std;
unordered_map<string, int> teamScores(const vector<vector<string>>& matches) {
unordered_map<string, int> scores;
for (const auto& match : matches) {
string team1 = match[0], team2 = match[1];
int score1 = stoi(match[2]), score2 = stoi(match[3]);
if (score1 > score2) {
scores[team1] += 3;
scores[team2] += 0;
} else if (score1 < score2) {
scores[team1] += 0;
scores[team2] += 3;
} else {
scores[team1] += 1;
scores[team2] += 1;
}
}
return scores;
}
import java.util.*;
public class Solution {
public Map<String, Integer> teamScores(List<List<String>> matches) {
Map<String, Integer> scores = new HashMap<>();
for (List<String> match : matches) {
String team1 = match.get(0), team2 = match.get(1);
int score1 = Integer.parseInt(match.get(2)), score2 = Integer.parseInt(match.get(3));
scores.putIfAbsent(team1, 0);
scores.putIfAbsent(team2, 0);
if (score1 > score2) {
scores.put(team1, scores.get(team1) + 3);
} else if (score1 < score2) {
scores.put(team2, scores.get(team2) + 3);
} else {
scores.put(team1, scores.get(team1) + 1);
scores.put(team2, scores.get(team2) + 1);
}
}
return scores;
}
}
function teamScores(matches) {
const scores = {};
for (const match of matches) {
const [team1, team2, score1, score2] = match;
if (!(team1 in scores)) scores[team1] = 0;
if (!(team2 in scores)) scores[team2] = 0;
if (score1 > score2) {
scores[team1] += 3;
} else if (score1 < score2) {
scores[team2] += 3;
} else {
scores[team1] += 1;
scores[team2] += 1;
}
}
return scores;
}
matches
. Each element in matches
represents a match and is formatted as [team1, team2, score1, score2]
, where:
team1
and team2
are strings representing the names of the two teams that played.score1
and score2
are integers representing the number of goals scored by team1
and team2
respectively.matches
:
score1 > score2
, award 3 points to team1
.score1 < score2
, award 3 points to team2
.score1 == score2
, award 1 point to each team.This approach is efficient because each match is processed exactly once and updating the hash map is a constant-time operation.
matches = [ ["A", "B", 2, 1], ["A", "C", 1, 1], ["B", "C", 0, 3] ]Step-by-step:
{"A": 4, "B": 0, "C": 4}