#107. 数组重排:4后跟5

数组重排:4后跟5

Rearrange Array: 4 Followed by 5

Background

In a data organization task, you are required to rearrange a special sequence of numbers. The numbers in this sequence need to conform to a specific pattern to ensure data correctness and usability.

Problem Description

(This is a slightly harder version of the fix34 problem.) Return an array that contains exactly the same numbers as the given array, but rearranged so that every 44 is immediately followed by a 55. Do not move the 44's, but every other number may move. The array contains the same number of 44's and 55's, and every 44 has a number after it that is not a 44. In this version, 55's may appear anywhere in the original array.

Input Format

Input is given from standard input in the following format.

An integer array, representing the original sequence.

Output Format

Output is printed to standard output in the following format.

An integer array, representing the rearranged sequence.

Sample

[5 4 9 4 9 5]
[9, 4, 5, 4, 5, 9]
[1 4 1 5]
[1, 4, 5, 1]
[1 4 1 5 5 4 1]
[1, 4, 5, 1, 1, 4, 5]

Sample Explanation

For Sample 1: The original array is [5, 4, 9, 4, 9, 5]. Here, 44s are at indices 11 and 33. We need to place 55s after the 44s. In the original array, the 55s at indices 00 and 55 are "free" (i.e., they are not preceded by a 44). The 99s at indices 22 and 44 need to be moved to make space for 55s. Ultimately, the 55 at index 00 is moved to index 22, and the 55 at index 55 is moved to index 44. The original 99s at indices 22 and 44 are moved to indices 00 and 55 respectively, resulting in [9, 4, 5, 4, 5, 9].

Constraints

Time limit: 11s, Memory limit: 10241024 KiB for each test case.