跳转至

3667. Sort Array By Absolute Value 🔒

题目描述

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 if x >= 0
  • -x if x < 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

解法

方法一:自定义排序

我们可以使用自定义的排序函数来对数组进行排序,排序的依据是每个元素的绝对值。

时间复杂度 \(O(n \times \log n)\),空间复杂度 \(O(\log n)\)。其中 \(n\) 是数组 \(\textit{nums}\) 的长度。

1
2
3
class Solution:
    def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
        return sorted(nums, key=lambda x: abs(x))
1
2
3
4
5
6
7
8
9
class Solution {
    public int[] sortByAbsoluteValue(int[] nums) {
        return Arrays.stream(nums)
            .boxed()
            .sorted(Comparator.comparingInt(Math::abs))
            .mapToInt(Integer::intValue)
            .toArray();
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
public:
    vector<int> sortByAbsoluteValue(vector<int>& nums) {
        sort(nums.begin(), nums.end(), [](int a, int b) {
            return abs(a) < abs(b);
        });
        return nums;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func sortByAbsoluteValue(nums []int) []int {
    slices.SortFunc(nums, func(a, b int) int {
        return abs(a) - abs(b)
    })
    return nums
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
1
2
3
function sortByAbsoluteValue(nums: number[]): number[] {
    return nums.sort((a, b) => Math.abs(a) - Math.abs(b));
}
1
2
3
4
5
6
impl Solution {
    pub fn sort_by_absolute_value(mut nums: Vec<i32>) -> Vec<i32> {
        nums.sort_by_key(|&x| x.abs());
        nums
    }
}

评论