diff --git a/problems/1365.有多少小于当前数字的数字.md b/problems/1365.有多少小于当前数字的数字.md index 69654930..9f282209 100644 --- a/problems/1365.有多少小于当前数字的数字.md +++ b/problems/1365.有多少小于当前数字的数字.md @@ -156,6 +156,7 @@ Go: JavaScript: ```javascript +// 方法一:使用哈希表记录位置 var smallerNumbersThanCurrent = function(nums) { const map = new Map();// 记录数字 nums[i] 有多少个比它小的数字 const res = nums.slice(0);//深拷贝nums @@ -171,9 +172,27 @@ var smallerNumbersThanCurrent = function(nums) { } 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) * B站视频:[代码随想录](https://space.bilibili.com/525438321)