LeetCode 题解工作台

矩阵中的幸运数

给你一个 m x n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。 幸运数 是指矩阵中满足同时下列两个条件的元素: 在同一行的所有元素中最小 在同一列的所有元素中最大 示例 1: 输入: matrix = [[3,7,8],[9,11,13],[15,16,17]] …

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们可以使用两个数组 和 记录矩阵中每一行的最小值和每一列的最大值,然后遍历矩阵中的每一个元素,检查该元素是否为所在行的最小值且为所在列的最大值,如果是则该元素为幸运数,我们将其加入答案数组。 遍历结束后,我们返回答案数组即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 m x n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。

幸运数 是指矩阵中满足同时下列两个条件的元素:

  • 在同一行的所有元素中最小
  • 在同一列的所有元素中最大

 

示例 1:

输入:matrix = [[3,7,8],[9,11,13],[15,16,17]]
输出:[15]
解释:15 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。

示例 2:

输入:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
输出:[12]
解释:12 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。

示例 3:

输入:matrix = [[7,8],[1,2]]
输出:[7]
解释:7 是唯一的幸运数字,因为它是行中的最小值,列中的最大值。

 

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= n, m <= 50
  • 1 <= matrix[i][j] <= 105
  • 矩阵中的所有元素都是不同的
lightbulb

解题思路

方法一:维护行最小值和列最大值

我们可以使用两个数组 rowsrowscolscols 记录矩阵中每一行的最小值和每一列的最大值,然后遍历矩阵中的每一个元素,检查该元素是否为所在行的最小值且为所在列的最大值,如果是则该元素为幸运数,我们将其加入答案数组。

遍历结束后,我们返回答案数组即可。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m+n)O(m + n)。其中 mmnn 分别是矩阵的行数和列数。

1
2
3
4
5
6
class Solution:
    def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
        rows = {min(row) for row in matrix}
        cols = {max(col) for col in zip(*matrix)}
        return list(rows & cols)
speed

复杂度分析

指标
时间O(N * M)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate can efficiently identify the row minimums and column maximums.

  • question_mark

    They correctly validate the lucky number condition for each element.

  • question_mark

    They optimize the solution by ensuring minimal space usage.

warning

常见陷阱

外企场景
  • error

    Failing to identify the correct row minimums or column maximums, leading to incorrect results.

  • error

    Not properly validating that a row minimum is also the column maximum.

  • error

    Using excessive space by storing unnecessary intermediate data or using complex data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the matrix has non-distinct values? How would the solution change?

  • arrow_right_alt

    Can the matrix contain negative numbers? If so, how does it affect the solution?

  • arrow_right_alt

    What if we have to find lucky numbers for submatrices instead of the entire matrix?

help

常见问题

外企场景

矩阵中的幸运数题解:数组·matrix | LeetCode #1380 简单