From d91233d0443753b747d139e00b081fa4f4c39fb1 Mon Sep 17 00:00:00 2001 From: huaqi <2931246464@qq.com> Date: Tue, 30 Aug 2022 21:18:16 +0800 Subject: [PATCH] =?UTF-8?q?0977.=E6=9C=89=E5=BA=8F=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E5=B9=B3=E6=96=B9-typescript=E7=89=88=E6=9C=AC-?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index eb9f42b1..501b9a42 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -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; }; ```