From 44a3e351f09b4f02ba57b19fcb33c3e4cb3d07e9 Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Wed, 1 Dec 2021 20:10:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200977=20=E6=9C=89=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9=20JavaScript?= =?UTF-8?q?=E7=89=88=E6=9C=AC=20=E6=9B=B4=E5=8A=A0=E7=AE=80=E6=B4=81?= =?UTF-8?q?=E9=AB=98=E6=95=88=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 37 +++++++++++++------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index b1e04c4e..6616ba8c 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -199,27 +199,26 @@ impl Solution { Javascript: ```Javascript /** - * @desc two pointers solution - * @link https://leetcode-cn.com/problems/squares-of-a-sorted-array/ - * @param nums Array e.g. [-4,-1,0,3,10] - * @return {array} e.g. [0,1,9,16,100] + * @param {number[]} nums + * @return {number[]} */ -const sortedSquares = function (nums) { - let res = [] - for (let i = 0, j = nums.length - 1; i <= j;) { - const left = Math.abs(nums[i]) - const right = Math.abs(nums[j]) - if (right > left) { - // push element to the front of the array - res.unshift(right * right) - j-- - } else { - res.unshift(left * left) - i++ - } +var sortedSquares = function(nums) { + let n = nums.length; + let res = new Array(n).fill(0); + let i = 0, j = n - 1, k = n - 1; + while (i <= j) { + let left = nums[i] * nums[i], + right = nums[j] * nums[j]; + if (left < right) { + res[k--] = right; + j--; + } else { + res[k--] = left; + i++; + } } - return res - } + return res; +}; ``` Swift: