Skip to content

Commit 6287b67

Browse files
authored
添加 1365 有多少个小于当前数字的数字 JavaScript版本不使用哈希表的解法
1 parent 7bb935c commit 6287b67

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

problems/1365.有多少小于当前数字的数字.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ Go:
156156

157157
JavaScript:
158158
```javascript
159+
// 方法一:使用哈希表记录位置
159160
var smallerNumbersThanCurrent = function(nums) {
160161
const map = new Map();// 记录数字 nums[i] 有多少个比它小的数字
161162
const res = nums.slice(0);//深拷贝nums
@@ -171,9 +172,27 @@ var smallerNumbersThanCurrent = function(nums) {
171172
}
172173
return res;
173174
};
175+
176+
// 方法二:不使用哈希表,只使用一个额外数组
177+
/**
178+
* @param {number[]} nums
179+
* @return {number[]}
180+
*/
181+
var smallerNumbersThanCurrent = function(nums) {
182+
let array = [...nums]; // 深拷贝
183+
// 升序排列,此时数组元素下标即是比他小的元素的个数
184+
array = array.sort((a, b) => a-b);
185+
let res = [];
186+
nums.forEach( x => {
187+
// 即使元素重复也不怕,indexOf 只返回找到的第一个元素的下标
188+
res.push(array.indexOf(x));
189+
})
190+
return res;
191+
};
174192
```
175193

176194

195+
177196
-----------------------
178197
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
179198
* B站视频:[代码随想录](https://space.bilibili.com/525438321)

0 commit comments

Comments
 (0)