Problem
You are given a 0-indexed integer array nums
. Rearrange the values of
nums
according to the following rules:
- Sort the values at odd indices of
nums
in non-increasing order.- For example, if
nums = [4,**_1_** ,2,_**3**_]
before this step, it becomes[4,_**3**_ ,2,**_1_**]
after. The values at odd indices1
and3
are sorted in non-increasing order.
- For example, if
- Sort the values at even indices of
nums
in non-decreasing order.- For example, if
nums = [_**4**_ ,1,_**2**_ ,3]
before this step, it becomes[_**2**_ ,1,_**4**_ ,3]
after. The values at even indices0
and2
are sorted in non-decreasing order.
- For example, if
Return the array formed after rearranging the values of nums
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 100
1 <= nums[i] <= 100
Solution
Method 1 - Separate, Sort, and Merge
Intuition
Extract elements at even and odd indices separately, sort them according to their requirements (even indices ascending, odd indices descending), then place them back in their respective positions.
Approach
- Separate elements at even indices and odd indices into different arrays
- Sort even-indexed elements in ascending order (non-decreasing)
- Sort odd-indexed elements in descending order (non-increasing)
- Merge the sorted arrays back into the result, maintaining index parity
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
where n is the length of the array (due to sorting operations) - 🧺 Space complexity:
O(n)
for storing the separated even and odd elements