3667. Sort Array By Absolute Value π
Description
You are given an integer array nums
.
Rearrange elements of nums
in non-decreasing order of their absolute value.
Return any rearranged array that satisfies this condition.
Note: The absolute value of an integer x is defined as:
x
ifx >= 0
-x
ifx < 0
Example 1:
Input: nums = [3,-1,-4,1,5]
Output: [-1,1,3,-4,5]
Explanation:
- The absolute values of elements in
nums
are 3, 1, 4, 1, 5 respectively. - Rearranging them in increasing order, we get 1, 1, 3, 4, 5.
- This corresponds to
[-1, 1, 3, -4, 5]
. Another possible rearrangement is[1, -1, 3, -4, 5].
Example 2:
Input: nums = [-100,100]
Output: [-100,100]
Explanation:
- The absolute values of elements in
nums
are 100, 100 respectively. - Rearranging them in increasing order, we get 100, 100.
- This corresponds to
[-100, 100]
. Another possible rearrangement is[100, -100]
.
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100
Solutions
Solution 1: Custom Sorting
We can use a custom sorting function to sort the array, where the sorting criterion is the absolute value of each element.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\), where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 |
|
1 2 3 4 5 6 |
|