Files
leetcode/docs/(welcome)/array/1636.mdx
T

47 lines
1.2 KiB
Plaintext

---
title: LC-1636
description: Sort Array by Increasing Frequency
---
## Examples
| Input | Output |
| ---------------------- | ---------------------- |
| `[1,1,2,2,2,3]` | `[3,1,1,2,2,2]` |
| `[2,3,1,3,2]` | `[1,3,3,2,2]` |
| `[-1,1,-6,4,5,-6,1,4,1]` | `[5,-1,4,4,-6,-6,1,1,1]` |
## Hints
<Accordion type="single">
<AccordionItem title="Constraints">
Constraints:
• `1 <= nums.length <= 100`
• `-100 <= nums[i] <= 100`
</AccordionItem>
<AccordionItem title="Problem Statement">
Given an array of integers nums, sort the array in increasing order based on the frequency of the values.
If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
</AccordionItem>
</Accordion>
## Solution
```js
/**
* @param {number[]} nums
* @return {number[]}
*/
var frequencySort = function (nums) {
// Default for Hammer
const freq = {};
for (let n of nums) freq[n] = (freq[n] || 0) + 1;
// Problem Specific
// Sort ascending by frequency; ties break by larger value first
return nums.sort((a, b) => freq[a] - freq[b] || b - a);
};
```