LeetCode 题解工作台

排序方式

给定一个数组 arr 和一个函数 fn ,返回一个排序后的数组 sortedArr 。你可以假设 fn 只返回数字,并且这些数字决定了 sortedArr 的排序顺序。 sortedArr 必须按照 fn 的输出值 升序 排序。 你可以假设对于给定的数组, fn 不会返回重复的数字。 示例 1: 输…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · 排序·by·core·interview·pattern

bolt

答案摘要

function sortBy(arr: any[], fn: Function): any[] { return arr.sort((a, b) => fn(a) - fn(b));

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 排序·by·core·interview·pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个数组 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
lightbulb

解题思路

方法一

1
2
3
4
function sortBy(arr: any[], fn: Function): any[] {
    return arr.sort((a, b) => fn(a) - fn(b));
}
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

排序方式题解:排序·by·core·interview·pa… | LeetCode #2724 简单