Class Solution
-
- All Implemented Interfaces:
public final class Solution3072 - Distribute Elements Into Two Arrays II.
Hard
You are given a 1-indexed array of integers
numsof lengthn.We define a function
greaterCountsuch thatgreaterCount(arr, val)returns the number of elements inarrthat are strictly greater thanval.You need to distribute all the elements of
numsbetween two arraysarr1andarr2usingnoperations. In the first operation, appendnums[1]toarr1. In the second operation, appendnums[2]toarr2. Afterwards, in the <code>i<sup>th</sup></code> operation:If
greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i]), appendnums[i]toarr1.If
greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i]), appendnums[i]toarr2.If
greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i]), appendnums[i]to the array with a lesser number of elements.If there is still a tie, append
nums[i]toarr1.
The array
resultis formed by concatenating the arraysarr1andarr2. For example, ifarr1 == [1,2,3]andarr2 == [4,5,6], thenresult = [1,2,3,4,5,6].Return the integer array
result.Example 1:
Input: nums = 2,1,3,3
Output: 2,3,1,3
Explanation: After the first 2 operations, arr1 = 2 and arr2 = 1.
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays.
Also, the lengths are equal, hence, append nums3 to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums4 to arr2.
After 4 operations, arr1 = 2,3 and arr2 = 1,3. Hence, the array result formed by concatenation is 2,3,1,3.
Example 2:
Input: nums = 5,14,3,1,2
Output: 5,3,1,2,14
Explanation: After the first 2 operations, arr1 = 5 and arr2 = 14.
In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums3 to arr1.
In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums4 to arr1. In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums5 to arr1.
zAfter 5 operations, arr1 = 5,3,1,2 and arr2 = 14. Hence, the array result formed by concatenation is 5,3,1,2,14.
Example 3:
Input: nums = 3,3,3,3
Output: 3,3,3,3
Explanation: At the end of 4 operations, arr1 = 3,3 and arr2 = 3,3. Hence, the array result formed by concatenation is 3,3,3,3.
Constraints:
<code>3 <= n <= 10<sup>5</sup></code>
<code>1 <= numsi<= 10<sup>9</sup></code>
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntArrayresultArray(IntArray source)-
-
Method Detail
-
resultArray
final IntArray resultArray(IntArray source)
-
-
-
-