File tree Expand file tree Collapse file tree 1 file changed +14
-8
lines changed Expand file tree Collapse file tree 1 file changed +14
-8
lines changed Original file line number Diff line number Diff line change @@ -239,18 +239,24 @@ Typescript:
239
239
240
240
``` typescript
241
241
function sortedSquares(nums : number []): number [] {
242
- let left: number = 0 , right: number = nums .length - 1 ;
243
- let resArr: number [] = new Array (nums .length );
244
- let resArrIndex: number = resArr .length - 1 ;
242
+ const ans: number [] = [];
243
+ let left = 0 ,
244
+ right = nums .length - 1 ;
245
+
245
246
while (left <= right ) {
246
- if (Math .abs (nums [left ]) < Math .abs (nums [right ])) {
247
- resArr [resArrIndex ] = nums [right -- ] ** 2 ;
247
+ // 右侧的元素不需要取绝对值,nums 为非递减排序的整数数组
248
+ // 在同为负数的情况下,左侧的平方值一定大于右侧的平方值
249
+ if (Math .abs (nums [left ]) > nums [right ]) {
250
+ // 使用 Array.prototype.unshift() 直接在数组的首项插入当前最大值
251
+ ans .unshift (nums [left ] ** 2 );
252
+ left ++ ;
248
253
} else {
249
- resArr [resArrIndex ] = nums [left ++ ] ** 2 ;
254
+ ans .unshift (nums [right ] ** 2 );
255
+ right -- ;
250
256
}
251
- resArrIndex -- ;
252
257
}
253
- return resArr ;
258
+
259
+ return ans ;
254
260
};
255
261
```
256
262
You can’t perform that action at this time.
0 commit comments