Unicorns VO OA 面试真题解析:交替正负数数组重排

18次阅读
没有评论

You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

You should return the array of nums such that the array follows these conditions:

  • Every consecutive pair of integers have opposite signs.
  • For all integers with the same sign, the order in which they were present in nums is preserved.
  • The rearranged array begins with a positive integer.

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

Example 1:

Input: nums = [3, 1, -2, -5, 2, -4]
Output: [3, -2, 1, -5, 2, -4]
Explanation:
The positive integers in nums are [3, 1, 2].
The negative integers are [-2, -5, -4].

这道题要求把一个长度为偶数、且正负数数量相等的数组重排成“正数、负数、正数、负数 …”交替出现,并且同号元素之间的相对顺序不能变。最直接的做法是先按遍历顺序分别收集所有正数和负数,再按照偶数位放正数、奇数位放负数的方式重新组装数组,这样既能保证交替,也能满足稳定性要求。

正文完
 0