From cc2c2adb0987a5e2e82eed75a93be068da6388a4 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Wed, 11 May 2022 16:03:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200977.=E6=9C=89=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9.md=20Scala?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 24276bcf..0e79a3d6 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -358,7 +358,41 @@ class Solution { } } ``` +Scala: +双指针: +```scala +object Solution { + def sortedSquares(nums: Array[Int]): Array[Int] = { + val res: Array[Int] = new Array[Int](nums.length) + var top = nums.length - 1 + var i = 0 + var j = nums.length - 1 + while (i <= j) { + if (nums(i) * nums(i) <= nums(j) * nums(j)) { + // 当左侧平方小于等于右侧,res数组顶部放右侧的平方,并且top下移,j左移 + res(top) = nums(j) * nums(j) + top -= 1 + j -= 1 + } else { + // 当左侧平方大于右侧,res数组顶部放左侧的平方,并且top下移,i右移 + res(top) = nums(i) * nums(i) + top -= 1 + i += 1 + } + } + res + } +} +``` +骚操作(暴力思路): +```scala +object Solution { + def sortedSquares(nums: Array[Int]): Array[Int] = { + nums.map(x=>{x*x}).sortWith(_ < _) + } +} +``` -----------------------