LeetCode 题解工作台
数组串联
给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 的 i ,满足下述所有要求: ans[i] == nums[i] ans[i + n] == nums[i] 具体而言, ans 由两个 nums 数组 串联 形成…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
我们直接根据题目描述模拟,将 中的元素依次添加到答案数组中,然后再将 中的元素再次添加到答案数组中。 时间复杂度 ,空间复杂度 。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 <= i < n 的 i ,满足下述所有要求:
ans[i] == nums[i]ans[i + n] == nums[i]
具体而言,ans 由两个 nums 数组 串联 形成。
返回数组 ans 。
示例 1:
输入:nums = [1,2,1] 输出:[1,2,1,1,2,1] 解释:数组 ans 按下述方式形成: - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]] - ans = [1,2,1,1,2,1]
示例 2:
输入:nums = [1,3,2,1] 输出:[1,3,2,1,1,3,2,1] 解释:数组 ans 按下述方式形成: - ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]] - ans = [1,3,2,1,1,3,2,1]
提示:
n == nums.length1 <= n <= 10001 <= nums[i] <= 1000
解题思路
方法一:模拟
我们直接根据题目描述模拟,将 中的元素依次添加到答案数组中,然后再将 中的元素再次添加到答案数组中。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums + nums
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate an understanding of basic array manipulation.
- question_mark
Look for familiarity with Python list operations, like concatenation or replication.
- question_mark
Candidates may try to optimize space by simulating the process in-place.
常见陷阱
外企场景- error
Not considering edge cases such as very small arrays or arrays with repeating elements.
- error
Over-complicating the solution with unnecessary operations.
- error
Not optimizing space usage when memory constraints are part of the interview context.
进阶变体
外企场景- arrow_right_alt
Create a solution with in-place operations (no additional space used).
- arrow_right_alt
Modify the solution to handle larger inputs efficiently.
- arrow_right_alt
Consider alternative programming languages and their array manipulation capabilities.