mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1610 from hua-qi/master
0977.有序数组的平方-typescript版本-优化写法
This commit is contained in:
@ -239,18 +239,24 @@ Typescript:
|
||||
|
||||
```typescript
|
||||
function sortedSquares(nums: number[]): number[] {
|
||||
let left: number = 0, right: number = nums.length - 1;
|
||||
let resArr: number[] = new Array(nums.length);
|
||||
let resArrIndex: number = resArr.length - 1;
|
||||
const ans: number[] = [];
|
||||
let left = 0,
|
||||
right = nums.length - 1;
|
||||
|
||||
while (left <= right) {
|
||||
if (Math.abs(nums[left]) < Math.abs(nums[right])) {
|
||||
resArr[resArrIndex] = nums[right--] ** 2;
|
||||
// 右侧的元素不需要取绝对值,nums 为非递减排序的整数数组
|
||||
// 在同为负数的情况下,左侧的平方值一定大于右侧的平方值
|
||||
if (Math.abs(nums[left]) > nums[right]) {
|
||||
// 使用 Array.prototype.unshift() 直接在数组的首项插入当前最大值
|
||||
ans.unshift(nums[left] ** 2);
|
||||
left++;
|
||||
} else {
|
||||
resArr[resArrIndex] = nums[left++] ** 2;
|
||||
ans.unshift(nums[right] ** 2);
|
||||
right--;
|
||||
}
|
||||
resArrIndex--;
|
||||
}
|
||||
return resArr;
|
||||
|
||||
return ans;
|
||||
};
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user