高级农民
- 积分
- 4019
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-1-22
- 最后登录
- 1970-1-1
|
3667. Sort Array By Absolute Value
Solved
Easy
Topics
Hint
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].
我的解法太麻烦,更好的方法是,直接用内置函数,或者用 装饰者模式 (Decorate-Sort-Undecorate)
这其实就是 Python 内部 key 参数的底层思想,也被称为 DSU 模式。
思路:
装饰 (Decorate): 将数组转换为一个元组列表,元组的第一个元素是“排序依据”(绝对值),第二个是“原始值”。
排序 (Sort): 对这个元组列表进行默认排序。
去装饰 (Undecorate): 提取出原始值。
我的原始解法,太繁琐。- class Solution:
- def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
- absSet = set()
- absDict = defaultdict(list)
- for n in nums:
- absSet.add(abs(n))
- absDict[abs(n)].append(n)
- absList = [x for x in absSet]
- absList.sort()
- res = []
- for a in absList:
- res += absDict[a]
-
- return res
-
复制代码 用 Python 内置函数 sort with key- class Solution:
- def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
- # 直接原地排序,使用 abs 函数作为排序的依据
- # 时间复杂度: O(n log n)
- # 空间复杂度: O(1) 或 O(n) 取决于排序算法实现
- nums.sort(key=abs)
- return nums
复制代码 不用 sort with key,可以用 装饰者模式 (Decorate-Sort-Undecorate)
这其实就是 Python 内部 key 参数的底层思想,也被称为 DSU 模式。
思路:
装饰 (Decorate): 将数组转换为一个元组列表,元组的第一个元素是“排序依据”(绝对值),第二个是“原始值”。
排序 (Sort): 对这个元组列表进行默认排序。
去装饰 (Undecorate): 提取出原始值。- class Solution:
- def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
- # 1. 构造包含 (绝对值, 原始值) 的元组列表
- # 比如 [3, -1] -> [(3, 3), (1, -1)]
- decorated = [(abs(x), x) for x in nums]
-
- # 2. 对元组进行排序
- # Python 排序元组时,会先比第一个元素,若相同再比第二个
- decorated.sort()
-
- # 3. 提取排序后的原始值
- return [pair[1] for pair in decorated]
复制代码 或者最 raw 的手写 quick sort- class Solution:
- def sortByAbsoluteValue(self, nums: List[int]) -> List[int]:
- def quick_sort(arr):
- if len(arr) <= 1:
- return arr
- pivot = arr[len(arr) // 2]
-
- # 修改这里的比较逻辑:对比的是 abs(x)
- left = [x for x in arr if abs(x) < abs(pivot)]
- middle = [x for x in arr if abs(x) == abs(pivot)]
- right = [x for x in arr if abs(x) > abs(pivot)]
-
- return quick_sort(left) + middle + quick_sort(right)
-
- return quick_sort(nums)
复制代码 |
|