mirror of
https://gitee.com/coder-xiaomo/leetcode-problemset
synced 2025-01-10 18:48:13 +08:00
38 lines
1.7 KiB
HTML
38 lines
1.7 KiB
HTML
<p>Given an array <code>arr</code> and a function <code>fn</code>, return a sorted array <code>sortedArr</code>. You can assume <code>fn</code> only returns numbers and those numbers determine the sort order of <code>sortedArr</code>. <code>sortedArray</code> must be sorted in <strong>ascending order</strong> by <code>fn</code> output.</p>
|
|
|
|
<p>You may assume that <code>fn</code> will never duplicate numbers for a given array.</p>
|
|
|
|
<p> </p>
|
|
<p><strong class="example">Example 1:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong> arr = [5, 4, 1, 2, 3], fn = (x) => x
|
|
<strong>Output:</strong> [1, 2, 3, 4, 5]
|
|
<strong>Explanation:</strong> fn simply returns the number passed to it so the array is sorted in ascending order.
|
|
</pre>
|
|
|
|
<p><strong class="example">Example 2:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong> arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
|
|
<strong>Output:</strong> [{"x": -1}, {"x": 0}, {"x": 1}]
|
|
<strong>Explanation:</strong> fn returns the value for the "x" key. So the array is sorted based on that value.
|
|
</pre>
|
|
|
|
<p><strong class="example">Example 3:</strong></p>
|
|
|
|
<pre>
|
|
<strong>Input:</strong> arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]
|
|
<strong>Output:</strong> [[10, 1], [5, 2], [3, 4]]
|
|
<strong>Explanation:</strong> arr is sorted in ascending order by number at index=1.
|
|
</pre>
|
|
|
|
<p> </p>
|
|
<p><strong>Constraints:</strong></p>
|
|
|
|
<ul>
|
|
<li><code>arr is a valid JSON array</code></li>
|
|
<li><code>fn is a function that returns a number</code></li>
|
|
<li><code>1 <= arr.length <= 5 * 10<sup>5</sup></code></li>
|
|
</ul>
|