mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
56 lines
1.3 KiB
Plaintext
56 lines
1.3 KiB
Plaintext
---
|
|
title: LC-1365
|
|
description: How Many Numbers Are Smaller Than the Current Number
|
|
---
|
|
|
|
## Examples
|
|
|
|
| Input | Output |
|
|
| ---------------- | -------------------- |
|
|
| `[8,1,2,2,3]` | `[4,0,1,1,3]` |
|
|
| `[6,5,4,8]` | `[2,1,0,3]` |
|
|
| `[7,7,7,7]` | `[0,0,0,0]` |
|
|
|
|
## Hints
|
|
|
|
<Accordion type="single">
|
|
<AccordionItem title="Constraints">
|
|
Constraints:
|
|
• `2 <= nums.length <= 500`
|
|
• `0 <= nums[i] <= 100`
|
|
</AccordionItem>
|
|
<AccordionItem title="Problem Statement">
|
|
Given the array nums, for each `nums[i]` find out how many numbers in the array are smaller than it.
|
|
That is, for each `nums[i]` you have to count the number of valid `j`'s such that `j != i` and `nums[j] < nums[i]`.
|
|
</AccordionItem>
|
|
</Accordion>
|
|
|
|
## Solution
|
|
|
|
```js
|
|
/**
|
|
* @param {number[]} nums
|
|
* @return {number[]}
|
|
*/
|
|
|
|
var smallerNumbersThanCurrent = function (nums) {
|
|
// Default for Hammer
|
|
const freq = {};
|
|
for (let n of nums) freq[n] = (freq[n] || 0) + 1;
|
|
const sorted = Object.keys(freq).sort((a, b) => a - b);
|
|
|
|
// Problem Specific
|
|
let count = 0;
|
|
let smaller = {};
|
|
|
|
// Iterate over sorted.
|
|
for (let num of sorted) {
|
|
smaller[num] = count;
|
|
count += freq[num];
|
|
}
|
|
|
|
// Map output
|
|
return nums.map((n) => smaller[n]);
|
|
};
|
|
```
|