How Many Numbers Are Smaller Than the Current Number LeetCode solution in JavaScript

1
var smallerNumbersThanCurrent = function (nums) {
2
let count,
3
ans = [];
4
/*Run a loop on each element excluding nums[i]
5
and compare it with nums[j] if it's large, then count++
6
else break;*/
7

8
for (let i = 0; i < nums.length; i++) {
9
let temp = nums[i],
10
count = 0;
11
for (let j = 0; j < nums.length; j++) {
12
if (i === j) continue;
13
if (temp > nums[j]) count++;
14
}
15
ans.push(count);
16
}
17
return ans;
18
};
19

20
//second way using objects:--->
21

22
var smallerNumbersThanCurrent = function (nums) {
23
let arr = [...nums],
24
ans = [];
25
arr.sort((a, b) => a - b);
26
let map = {};
27
map[arr[0]] = 0;
28
for (let i = 1; i < arr.length; i++) {
29
if (arr[i - 1] !== arr[i]) map[arr[i]] = i;
30
}
31
for (let i = 0; i < nums.length; i++) {
32
ans.push(map[nums[i]]);
33
}
34
return ans;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0