LeetCode 题解工作台
解压缩编码列表
给你一个以行程长度编码压缩的整数列表 nums 。 考虑每对相邻的两个元素 [freq, val] = [nums[2*i], nums[2*i+1]] (其中 i >= 0 ),每一对都表示解压后子列表中有 freq 个值为 val 的元素,你需要从左到右连接所有子列表以生成解压后的列表。 请你返…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们可以直接模拟题目描述的过程,从左到右遍历数组 ,每次取出两个数 和 ,然后将 重复 次,将这 个 加入答案数组即可。 时间复杂度 ,其中 是数组 的长度。我们只需要遍历一次数组 即可。忽略答案数组的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个以行程长度编码压缩的整数列表 nums 。
考虑每对相邻的两个元素 [freq, val] = [nums[2*i], nums[2*i+1]] (其中 i >= 0 ),每一对都表示解压后子列表中有 freq 个值为 val 的元素,你需要从左到右连接所有子列表以生成解压后的列表。
请你返回解压后的列表。
示例 1:
输入:nums = [1,2,3,4] 输出:[2,4,4,4] 解释:第一对 [1,2] 代表着 2 的出现频次为 1,所以生成数组 [2]。 第二对 [3,4] 代表着 4 的出现频次为 3,所以生成数组 [4,4,4]。 最后将它们串联到一起 [2] + [4,4,4] = [2,4,4,4]。
示例 2:
输入:nums = [1,1,2,3] 输出:[1,3,3]
提示:
2 <= nums.length <= 100nums.length % 2 == 01 <= nums[i] <= 100
解题思路
方法一:模拟
我们可以直接模拟题目描述的过程,从左到右遍历数组 ,每次取出两个数 和 ,然后将 重复 次,将这 个 加入答案数组即可。
时间复杂度 ,其中 是数组 的长度。我们只需要遍历一次数组 即可。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
return [nums[i + 1] for i in range(0, len(nums), 2) for _ in range(nums[i])]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate understands the run-length encoding and how to iterate through pairs.
- question_mark
Observe if the candidate uses list operations efficiently to minimize overhead.
- question_mark
Assess whether the candidate avoids excessive space usage by directly modifying the result.
常见陷阱
外企场景- error
Incorrectly handling the case where nums contains an odd number of elements or non-even pairs.
- error
Using inefficient techniques like repeated manual loops instead of list operations for value repetition.
- error
Not ensuring that the result list is built in an optimal way, possibly leading to high memory consumption.
进阶变体
外企场景- arrow_right_alt
Given an input of varying length, test if the solution scales with different amounts of input data.
- arrow_right_alt
Test the case with large frequency values to see if the solution can handle arrays with high expansion factors.
- arrow_right_alt
Introduce more complex encoding schemes with additional data types or constraints to test adaptability.