2924. Find Champion II #879
-
Topics: There are You are given the integer A directed edge from Team Return the team that will be the champion of the tournament if there is a unique champion, otherwise, return Notes
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to identify the team(s) with an in-degree of Let's implement this solution in PHP: 2924. Find Champion II <?php
/**
* @param Integer $n
* @param Integer[][] $edges
* @return Integer
*/
function findChampion($n, $edges) {
// Initialize in-degrees for all teams
$inDegree = array_fill(0, $n, 0);
// Calculate the in-degree for each team
foreach ($edges as $edge) {
$inDegree[$edge[1]]++;
}
// Find teams with in-degree 0
$candidates = [];
for ($i = 0; $i < $n; $i++) {
if ($inDegree[$i] == 0) {
$candidates[] = $i;
}
}
// If exactly one team has in-degree 0, return it; otherwise, return -1
return count($candidates) === 1 ? $candidates[0] : -1;
}
// Example 1
$n1 = 3;
$edges1 = [[0, 1], [1, 2]];
echo "Example 1 Output: " . findChampion($n1, $edges1) . PHP_EOL; // Output: 0
// Example 2
$n2 = 4;
$edges2 = [[0, 2], [1, 3], [1, 2]];
echo "Example 2 Output: " . findChampion($n2, $edges2) . PHP_EOL; // Output: -1
?> Explanation:
Example WalkthroughExample 1:
Example 2:
Complexity Analysis
This solution is efficient and works within the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to identify the team(s) with an in-degree of
0
in the given Directed Acyclic Graph (DAG). Teams with no incoming edges represent teams that no other team is stronger than, making them candidates for being the champion. If there is exactly one team with an in-degree of0
, it is the unique champion. If there are multiple or no such teams, the result is-1
.Let's implement this solution in PHP: 2924. Find Champion II