LeetCode 题解工作台
重新排列数组
给你一个数组 nums ,数组中有 2n 个元素,按 [x 1 ,x 2 ,...,x n ,y 1 ,y 2 ,...,y n ] 的格式排列。 请你将数组按 [x 1 ,y 1 ,x 2 ,y 2 ,...,x n ,y n ] 格式重新排列,返回重排后的数组。 示例 1: 输入: nums =…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们在 $[0, n)$ 的范围内遍历下标 ,每次取出 和 ,并将它们依次放入答案数组中。 遍历结束后,返回答案数组即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,...,xn,y1,y2,...,yn] 的格式排列。
请你将数组按 [x1,y1,x2,y2,...,xn,yn] 格式重新排列,返回重排后的数组。
示例 1:
输入:nums = [2,5,1,3,4,7], n = 3 输出:[2,3,5,4,1,7] 解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7]
示例 2:
输入:nums = [1,2,3,4,4,3,2,1], n = 4 输出:[1,4,2,3,3,2,4,1]
示例 3:
输入:nums = [1,1,2,2], n = 2 输出:[1,2,1,2]
提示:
1 <= n <= 500nums.length == 2n1 <= nums[i] <= 10^3
解题思路
方法一:模拟
我们在 的范围内遍历下标 ,每次取出 和 ,并将它们依次放入答案数组中。
遍历结束后,返回答案数组即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [x for pair in zip(nums[:n], nums[n:]) for x in pair]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate come up with a solution that processes the array in a single pass?
- question_mark
Does the candidate understand how to implement a two-pointer strategy?
- question_mark
Can the candidate handle space constraints by modifying the array in place?
常见陷阱
外企场景- error
Failing to handle the rearrangement correctly and ending up with an incorrect order.
- error
Using unnecessary extra space when the problem can be solved in-place.
- error
Not maintaining the correct pairing between elements from the two halves of the array.
进阶变体
外企场景- arrow_right_alt
What if the array contains more than two halves? Extend the problem to more parts.
- arrow_right_alt
What if the array elements are not strictly consecutive or are unsorted?
- arrow_right_alt
What if the input array is already partially shuffled? How would you handle this case?