2924. Find Champion II
Difficulty: Medium
Topics: Graph
There are n teams numbered from 0 to n - 1 in a tournament; each team is also a node in a DAG.
You are given the integer n and a 0-indexed 2D integer array edges of length m representing the DAG, where >dges[i] = [ui, vi] indicates that there is a directed edge from team ui to team vi in the graph.
A directed edge from a to b in the graph means that team a is stronger than team b and team b is weaker than team a.
Team a will be the champion of the tournament if there is no team b that is stronger than team a.
Return the team that will be the champion of the tournament if there is a unique champion, otherwise, return -1.
Notes
Example 1:
Example 2:
Constraints:
Hint:
Solution:
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 of 0, 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
Explanation:
Input Parsing:
- n is the number of teams.
- edges is the list of directed edges in the graph.
Initialize In-degree:
- Create an array inDegree of size n initialized to 0.
Calculate In-degree:
- For each edge [u, v], increment the in-degree of v (team v has one more incoming edge).
Find Candidates:
- Iterate through the inDegree array and collect indices where the in-degree is 0. These indices represent teams with no other stronger teams.
Determine Champion:
- If exactly one team has in-degree 0, it is the unique champion.
- If multiple teams or no teams have in-degree 0, return -1.
Example Walkthrough
Example 1:
Time Complexity:
Space Complexity:
This solution is efficient and works within the given constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Find Champion II. For more information, please follow other related articles on the PHP Chinese website!