Skip to content

2923. Find Champion I

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int findChampion(vector<vector<int>>& grid) {
    const int n = grid.size();
    int ans = -1;
    int count = 0;
    vector<int> inDegrees(n);

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        if (i == j)
          continue;
        grid[i][j] == 1 ? ++inDegrees[j] : ++inDegrees[i];
      }

    for (int i = 0; i < n; ++i)
      if (inDegrees[i] == 0) {
        ++count;
        ans = i;
      }

    return count > 1 ? -1 : ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int findChampion(int[][] grid) {
    final int n = grid.length;
    int ans = -1;
    int count = 0;
    int[] inDegrees = new int[n];

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        if (i == j)
          continue;
        if (grid[i][j] == 1)
          ++inDegrees[j];
        else
          ++inDegrees[i];
      }

    for (int i = 0; i < n; ++i)
      if (inDegrees[i] == 0) {
        ++count;
        ans = i;
      }

    return count > 1 ? -1 : ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def findChampion(self, grid: list[list[int]]) -> int:
    n = len(grid)
    inDegrees = [0] * n

    for i in range(n):
      for j in range(n):
        if i == j:
          continue
        if grid[i][j] == 1:
          inDegrees[j] += 1
        else:
          inDegrees[i] += 1

    return (-1 if inDegrees.count(0) > 1
            else inDegrees.index(0))