LeetCode 题解工作台
排序方式
给定一个数组 arr 和一个函数 fn ,返回一个排序后的数组 sortedArr 。你可以假设 fn 只返回数字,并且这些数字决定了 sortedArr 的排序顺序。 sortedArr 必须按照 fn 的输出值 升序 排序。 你可以假设对于给定的数组, fn 不会返回重复的数字。 示例 1: 输…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · 排序·by·core·interview·pattern
答案摘要
function sortBy(arr: any[], fn: Function): any[] { return arr.sort((a, b) => fn(a) - fn(b));
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 排序·by·core·interview·pattern 题型思路
题目描述
给定一个数组 arr 和一个函数 fn,返回一个排序后的数组 sortedArr。你可以假设 fn 只返回数字,并且这些数字决定了 sortedArr 的排序顺序。sortedArr 必须按照 fn 的输出值 升序 排序。
你可以假设对于给定的数组,fn 不会返回重复的数字。
示例 1:
输入:arr = [5, 4, 1, 2, 3], fn = (x) => x 输出:[1, 2, 3, 4, 5] 解释:fn 只是返回传入的数字,因此数组按升序排序。
示例 2:
输入:arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
输出:[{"x": -1}, {"x": 0}, {"x": 1}]
解释:fn 返回 "x" 键的值,因此数组根据该值排序。
示例 3:
输入:arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1] 输出:[[10, 1], [5, 2], [3, 4]] 解释:数组按照索引为 1 处的数字升序排序。
提示:
arr是一个有效的 JSON 数组fn是一个函数,返回一个数字1 <= arr.length <= 5 * 105
解题思路
方法一
function sortBy(arr: any[], fn: Function): any[] {
return arr.sort((a, b) => fn(a) - fn(b));
}
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(NlogN) due to the sorting operation, and space complexity is O(N) to store the mapped tuples for stable sorting based on function outputs. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Check if the candidate precomputes fn values to avoid repeated computation during sort.
- question_mark
Ask how the solution handles objects or nested arrays where fn extracts numeric keys or indices.
- question_mark
Watch for candidates using unstable sorts or ignoring the ascending order requirement tied to fn.
常见陷阱
外企场景- error
Calling fn multiple times during sorting can increase runtime unnecessarily.
- error
Sorting the original array without preserving element references can break object or nested array structures.
- error
Assuming fn outputs are not unique may lead to incorrect handling of duplicates, even if the problem guarantees uniqueness.
进阶变体
外企场景- arrow_right_alt
Sort descending by fn output instead of ascending, simply by reversing the comparator.
- arrow_right_alt
Sort by multiple functions sequentially, applying a primary and secondary fn for tie-breaking.
- arrow_right_alt
Handle arrays where fn may produce floating-point numbers, ensuring correct numeric sorting.