LeetCode 题解工作台

按符号重排数组

给你一个下标从 0 开始的整数数组 nums ,数组长度为 偶数 ,由数目 相等 的正整数和负整数组成。 你需要返回满足下述条件的数组 nums : 任意 连续 的两个整数 符号相反 对于符号相同的所有整数, 保留 它们在 nums 中的 顺序 。 重排后数组以正整数开头。 重排元素满足上述条件后,…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 双·指针·invariant

bolt

答案摘要

我们先创建一个长度为 的数组 ,然后使用两个指针 和 分别指向 的偶数下标和奇数下标,初始时 $i = 0$, $j = 1$。 遍历数组 ,如果当前元素 为正整数,则将 放入 ,并将 增加 ;否则将 放入 ,并将 增加 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums ,数组长度为 偶数 ,由数目 相等 的正整数和负整数组成。

你需要返回满足下述条件的数组 nums

  1. 任意 连续 的两个整数 符号相反
  2. 对于符号相同的所有整数,保留 它们在 nums 中的 顺序
  3. 重排后数组以正整数开头。

重排元素满足上述条件后,返回修改后的数组。

 

示例 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 * 105
  • nums.length偶数
  • 1 <= |nums[i]| <= 105
  • nums相等 数量的正整数和负整数组成

 

不需要原地进行修改。

lightbulb

解题思路

方法一:双指针

我们先创建一个长度为 nn 的数组 ans\textit{ans},然后使用两个指针 iijj 分别指向 ans\textit{ans} 的偶数下标和奇数下标,初始时 i=0i = 0, j=1j = 1

遍历数组 nums\textit{nums},如果当前元素 xx 为正整数,则将 xx 放入 ans[i]\textit{ans}[i],并将 ii 增加 22;否则将 xx 放入 ans[j]\textit{ans}[j],并将 jj 增加 22

最后返回 ans\textit{ans} 即可。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

按符号重排数组题解:双·指针·invariant | LeetCode #2149 中等