Rearrange Array Elements by Sign
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
Return the array of nums such that it follows all of 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
numsis preserved. - The rearranged array begins with a positive integer.
Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
It is not required to do the modifications in-place.
Example 1
Input
nums = [3,1,-2,-5,2,-4]Output
[3,-2,1,-5,2,-4]The positive integers are [3, 1, 2] and the negative integers are [-2, -5, -4], so preserving each sign's order while starting positive gives [3, -2, 1, -5, 2, -4].
Example 2
Input
nums = [-1,1]Output
[1,-1]1 is the only positive integer and -1 is the only negative integer, so nums is rearranged to [1, -1].
Constraints
- 2 <= nums.length <= 2 * 10^5
- nums.length is even
- 1 <= |nums[i]| <= 10^5
- nums consists of equal number of positive and negative integers.