575.Rearrange Positives and Negatives Alternately
Easy
Given an array of even length containing equally many positive and negative numbers (and no zeros), return a rearrangement in which positives and negatives alternate, starting with a positive. Within each sign, the values must keep their original order.
Keeping the original order within each group makes this a stableStable RearrangementA reordering that keeps equal-category elements in their original relative order. rearrangement. Because the final position of every value can be worked out in advance, the second solution uses two write pointersWrite PointerAn index that marks where the next value should be written in an output array. that each advance by two, filling the even and odd slots in a single pass.
Example 1:
Input: nums = [5,-2,9,4,-7,-1]
Output: [5,-2,9,-7,4,-1]
Example 2:
Input: nums = [-3,8]
Output: [8,-3]
+ 4 hidden test cases run on Submit.
Constraints:
- ●
2 ≤ nums.length ≤ 1000, and the length is even - ●
exactly half the values are positive and half are negative - ●
-1000000 ≤ nums[i] ≤ 1000000, nums[i] ≠ 0
nums =
[5, -2, 9, 4, -7, -1]