File tree Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Original file line number Diff line number Diff line change 156
156
157
157
JavaScript:
158
158
``` javascript
159
+ // 方法一:使用哈希表记录位置
159
160
var smallerNumbersThanCurrent = function (nums ) {
160
161
const map = new Map ();// 记录数字 nums[i] 有多少个比它小的数字
161
162
const res = nums .slice (0 );// 深拷贝nums
@@ -171,9 +172,27 @@ var smallerNumbersThanCurrent = function(nums) {
171
172
}
172
173
return res;
173
174
};
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
+ };
174
192
```
175
193
176
194
195
+
177
196
-----------------------
178
197
* 作者微信:[ 程序员Carl] ( https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw )
179
198
* B站视频:[ 代码随想录] ( https://space.bilibili.com/525438321 )
You can’t perform that action at this time.
0 commit comments