mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
47 lines
1.1 KiB
Plaintext
47 lines
1.1 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
|
|
|
|
<Accordions type="single">
|
|
<Accordion title="Constraints">
|
|
Constraints:
|
|
• `1 <= nums.length <= 100`
|
|
• `-100 <= nums[i] <= 100`
|
|
</Accordion>
|
|
<Accordion 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.
|
|
</Accordion>
|
|
</Accordions>
|
|
|
|
## 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);
|
|
};
|
|
```
|