LeetCode 题解工作台

转换二维数组

给你一个整数数组 nums 。请你创建一个满足以下条件的二维数组: 二维数组应该 只 包含数组 nums 中的元素。 二维数组中的每一行都包含 不同 的整数。 二维数组的行数应尽可能 少 。 返回结果数组。如果存在多种答案,则返回其中任何一种。 请注意,二维数组的每一行上可以存在不同数量的元素。 示…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们先用一个数组或者哈希表 统计数组 中每个元素出现的次数。 然后遍历 ,对于每个元素 ,我们将其添加到答案列表中的第 行,第 行,第 行,...,第 行。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums 。请你创建一个满足以下条件的二维数组:

  • 二维数组应该 包含数组 nums 中的元素。
  • 二维数组中的每一行都包含 不同 的整数。
  • 二维数组的行数应尽可能

返回结果数组。如果存在多种答案,则返回其中任何一种。

请注意,二维数组的每一行上可以存在不同数量的元素。

 

示例 1:

输入:nums = [1,3,4,1,2,3,1]
输出:[[1,3,4,2],[1,3],[1]]
解释:根据题目要求可以创建包含以下几行元素的二维数组:
- 1,3,4,2
- 1,3
- 1
nums 中的所有元素都有用到,并且每一行都由不同的整数组成,所以这是一个符合题目要求的答案。
可以证明无法创建少于三行且符合题目要求的二维数组。

示例 2:

输入:nums = [1,2,3,4]
输出:[[4,3,2,1]]
解释:nums 中的所有元素都不同,所以我们可以将其全部保存在二维数组中的第一行。

 

提示:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= nums.length
lightbulb

解题思路

方法一:数组或哈希表

我们先用一个数组或者哈希表 cnt\textit{cnt} 统计数组 nums\textit{nums} 中每个元素出现的次数。

然后遍历 cnt\textit{cnt},对于每个元素 xx,我们将其添加到答案列表中的第 00 行,第 11 行,第 22 行,...,第 cnt[x]1\textit{cnt}[x]-1 行。

最后返回答案列表即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def findMatrix(self, nums: List[int]) -> List[List[int]]:
        cnt = Counter(nums)
        ans = []
        for x, v in cnt.items():
            for i in range(v):
                if len(ans) <= i:
                    ans.append([])
                ans[i].append(x)
        return ans
speed

复杂度分析

指标
时间complexity is O(N) since each element is checked against existing rows once using hash lookups. Space complexity is O(N) to store row sets and mapping of elements.
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expecting a hash table solution to track elements in rows.

  • question_mark

    Looking for efficient O(N) placement without nested loops over elements.

  • question_mark

    Will ask about handling multiple valid 2D array outputs and row length differences.

warning

常见陷阱

外企场景
  • error

    Trying to predefine the number of rows instead of dynamically creating them.

  • error

    Using nested loops without hash lookup, which increases runtime.

  • error

    Not ensuring each row contains distinct integers, violating the main condition.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allowing each row to contain at most K elements while keeping them distinct.

  • arrow_right_alt

    Returning the arrangement with the minimal number of rows instead of any valid output.

  • arrow_right_alt

    Permuting nums before placement to observe different valid 2D array outputs.

help

常见问题

外企场景

转换二维数组题解:数组·哈希·扫描 | LeetCode #2610 中等