mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加 1365 有多少个小于当前数字的数字 JavaScript版本不使用哈希表的解法
This commit is contained in:
@ -156,6 +156,7 @@ Go:
|
|||||||
|
|
||||||
JavaScript:
|
JavaScript:
|
||||||
```javascript
|
```javascript
|
||||||
|
// 方法一:使用哈希表记录位置
|
||||||
var smallerNumbersThanCurrent = function(nums) {
|
var smallerNumbersThanCurrent = function(nums) {
|
||||||
const map = new Map();// 记录数字 nums[i] 有多少个比它小的数字
|
const map = new Map();// 记录数字 nums[i] 有多少个比它小的数字
|
||||||
const res = nums.slice(0);//深拷贝nums
|
const res = nums.slice(0);//深拷贝nums
|
||||||
@ -171,9 +172,27 @@ var smallerNumbersThanCurrent = function(nums) {
|
|||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 方法二:不使用哈希表,只使用一个额外数组
|
||||||
|
/**
|
||||||
|
* @param {number[]} nums
|
||||||
|
* @return {number[]}
|
||||||
|
*/
|
||||||
|
var smallerNumbersThanCurrent = function(nums) {
|
||||||
|
let array = [...nums]; // 深拷贝
|
||||||
|
// 升序排列,此时数组元素下标即是比他小的元素的个数
|
||||||
|
array = array.sort((a, b) => a-b);
|
||||||
|
let res = [];
|
||||||
|
nums.forEach( x => {
|
||||||
|
// 即使元素重复也不怕,indexOf 只返回找到的第一个元素的下标
|
||||||
|
res.push(array.indexOf(x));
|
||||||
|
})
|
||||||
|
return res;
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
Reference in New Issue
Block a user