LeetCode 题解工作台
按符号重排数组
给你一个下标从 0 开始的整数数组 nums ,数组长度为 偶数 ,由数目 相等 的正整数和负整数组成。 你需要返回满足下述条件的数组 nums : 任意 连续 的两个整数 符号相反 对于符号相同的所有整数, 保留 它们在 nums 中的 顺序 。 重排后数组以正整数开头。 重排元素满足上述条件后,…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们先创建一个长度为 的数组 ,然后使用两个指针 和 分别指向 的偶数下标和奇数下标,初始时 $i = 0$, $j = 1$。 遍历数组 ,如果当前元素 为正整数,则将 放入 ,并将 增加 ;否则将 放入 ,并将 增加 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,数组长度为 偶数 ,由数目 相等 的正整数和负整数组成。
你需要返回满足下述条件的数组 nums:
- 任意 连续 的两个整数 符号相反
- 对于符号相同的所有整数,保留 它们在
nums中的 顺序 。 - 重排后数组以正整数开头。
重排元素满足上述条件后,返回修改后的数组。
示例 1:
输入:nums = [3,1,-2,-5,2,-4] 输出:[3,-2,1,-5,2,-4] 解释: nums 中的正整数是 [3,1,2] ,负整数是 [-2,-5,-4] 。 重排的唯一可行方案是 [3,-2,1,-5,2,-4],能满足所有条件。 像 [1,-2,2,-5,3,-4]、[3,1,2,-2,-5,-4]、[-2,3,-5,1,-4,2] 这样的其他方案是不正确的,因为不满足一个或者多个条件。
示例 2:
输入:nums = [-1,1] 输出:[1,-1] 解释: 1 是 nums 中唯一一个正整数,-1 是 nums 中唯一一个负整数。 所以 nums 重排为 [1,-1] 。
提示:
2 <= nums.length <= 2 * 105nums.length是 偶数1 <= |nums[i]| <= 105nums由 相等 数量的正整数和负整数组成
不需要原地进行修改。
解题思路
方法一:双指针
我们先创建一个长度为 的数组 ,然后使用两个指针 和 分别指向 的偶数下标和奇数下标,初始时 , 。
遍历数组 ,如果当前元素 为正整数,则将 放入 ,并将 增加 ;否则将 放入 ,并将 增加 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
ans = [0] * len(nums)
i, j = 0, 1
for x in nums:
if x > 0:
ans[i] = x
i += 2
else:
ans[j] = x
j += 2
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Does the candidate demonstrate an understanding of two-pointer techniques for separating positive and negative integers?
- question_mark
Can the candidate describe how they would handle large input sizes efficiently?
- question_mark
Does the candidate focus on maintaining the alternating pattern while ensuring minimal computational overhead?
常见陷阱
外企场景- error
Mixing up the order of positive and negative integers when swapping or rearranging them.
- error
Failing to consider edge cases, such as arrays with only two elements.
- error
Not maintaining the required alternating sign pattern after rearrangement.
进阶变体
外企场景- arrow_right_alt
Handling arrays with additional constraints, such as arrays of larger sizes.
- arrow_right_alt
Modifying the solution to handle other conditions, such as multiple positive-negative swaps.
- arrow_right_alt
Optimizing for space complexity, using in-place swapping or tracking positions more efficiently.