LeetCode 题解工作台

找到冠军 I

一场比赛中共有 n 支队伍,按从 0 到 n - 1 编号。 给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 且 i != j 的所有 i, j :如果 grid[i][j] == 1 ,那么 i 队比 j 队 强 ;否则, j 队比 i 队 强 。 在这场比…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们可以枚举每一支队伍 ,如果 队的每一场比赛都赢了,那么 队就是冠军,直接返回 即可。 时间复杂度 ,其中 是队伍数量。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

一场比赛中共有 n 支队伍,按从 0 到  n - 1 编号。

给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 <= i, j <= n - 1i != j 的所有 i, j :如果 grid[i][j] == 1,那么 i 队比 j ;否则,j 队比 i

在这场比赛中,如果不存在某支强于 a 队的队伍,则认为 a 队将会是 冠军

返回这场比赛中将会成为冠军的队伍。

 

示例 1:

输入:grid = [[0,1],[0,0]]
输出:0
解释:比赛中有两支队伍。
grid[0][1] == 1 表示 0 队比 1 队强。所以 0 队是冠军。

示例 2:

输入:grid = [[0,0,1],[1,0,1],[0,0,0]]
输出:1
解释:比赛中有三支队伍。
grid[1][0] == 1 表示 1 队比 0 队强。
grid[1][2] == 1 表示 1 队比 2 队强。
所以 1 队是冠军。

 

提示:

  • n == grid.length
  • n == grid[i].length
  • 2 <= n <= 100
  • grid[i][j] 的值为 01
  • 对于所有 i grid[i][i] 等于 0.
  • 对于满足 i != j 的所有 i, jgrid[i][j] != grid[j][i] 均成立
  • 生成的输入满足:如果 a 队比 b 队强,b 队比 c 队强,那么 a 队比 c 队强
lightbulb

解题思路

方法一:枚举

我们可以枚举每一支队伍 ii,如果 ii 队的每一场比赛都赢了,那么 ii 队就是冠军,直接返回 ii 即可。

时间复杂度 O(n2)O(n^2),其中 nn 是队伍数量。空间复杂度 O(1)O(1)

1
2
3
4
5
6
class Solution:
    def findChampion(self, grid: List[List[int]]) -> int:
        for i, row in enumerate(grid):
            if all(x == 1 for j, x in enumerate(row) if i != j):
                return i
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for candidates who can efficiently implement a solution using graph traversal techniques or matrix analysis.

  • question_mark

    Candidates should understand the problem's matrix-based structure and avoid unnecessary brute-force approaches.

  • question_mark

    Assess if the candidate can choose the most efficient algorithm depending on the given matrix size and constraints.

warning

常见陷阱

外企场景
  • error

    Failing to recognize the asymmetry of the matrix and attempting to solve it with incorrect assumptions about the data structure.

  • error

    Overcomplicating the solution by introducing unnecessary data structures or algorithms.

  • error

    Not optimizing the solution for larger values of n, leading to inefficient runtime for the problem's constraints.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Use a directed graph representation and explore different traversal methods to identify the champion.

  • arrow_right_alt

    Change the matrix to include additional constraints, such as teams with partial strengths against each other.

  • arrow_right_alt

    Introduce a scenario where ties can occur, and the algorithm must handle determining the champion under these conditions.

help

常见问题

外企场景

找到冠军 I题解:数组·matrix | LeetCode #2923 简单