Alternate Positive and Negative
mediumPlacement Coding+20 XPTime limit 2s
Rearrange the array so that non-negative and negative numbers alternate, starting with a non-negative number. Keep the original relative order inside each group. When one group runs out, append the rest of the other group in order. (Treat 0 as non-negative.)
[1, 2, 3, -4, -1, 4] becomes [1, -4, 2, -1, 3, 4].
Input:
- line 1:
n - line 2:
nintegers
Output: the rearranged array.
Constraints: 1 ≤ n ≤ 10⁵, −10⁹ ≤ values ≤ 10⁹.
Think about it: split the numbers into two lists (keeping order), then take one from each list in turn.
Sample input 1
6 1 2 3 -4 -1 4
Sample output 1
1 -4 2 -1 3 4
Sample input 2
5 -5 -2 5 2 4
Sample output 2
5 -5 2 -2 4
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).