Sort Array By Absolute Value
You are given an integer array nums.
Rearrange the elements of the array in non-decreasing order of their absolute values.
If two elements have the same absolute value, then place the smaller number first.
Return the rearranged array.
The absolute value of an integer x is defined as:
- x, if x ≥ 0
- -x, if x < 0
Example 1:
Input: nums = [4, -2, 0, -1, 3]
Output: [0, -1, -2, 3, 4]
Explanation:
- Absolute values → [4, 2, 0, 1, 3]
- Sorted by absolute value → [0, 1, 2, 3, 4]
- Final arrangement → [0, -1, -2, 3, 4]
Example 2:
Input: nums = [-7, 5, -3, 2]
Output: [2, -3, 5, -7]
Explanation:
- Absolute values → [7, 5, 3, 2]
- Sorted absolute values → [2, 3, 5, 7]
- Final result → [2, -3, 5, -7]
Now Your Turn!
Pick the correct output for the given inputInput: nums = [-5, 1, -2, 2]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ nums.length ≤ 100
- -100 ≤ nums[i] ≤ 100