0%

Leetcode 1365. How Many Numbers Are Smaller Than the Current Number

題目

1
2
3
4
5
6
7
8
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

解法思維

跑迴圈依序比大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const smallerNumbersThanCurrent = nums => {
let result = [];
let count = 0;

for (let i = 0; i < nums.length; i += 1) {
let cv = nums[i];

for (let j = 0; j < nums.length; j += 1) {
let num = nums[j];

if (cv > num) {
count++
}
}

result.push(count)
count = 0;
}

return result;
};

先用 sort()排序由小到大,再由indexOf查找位置,回傳結果

1
2
3
4
5
let smallerNumbersThanCurrent = (nums) =>{
let tp=Array.from(nums).sort((a,b)=>a-b)
let result=nums.map(x=>tp.indexOf(x))
return result
};