From 10b440ec27b814715dad23110b919c33d59403b6 Mon Sep 17 00:00:00 2001 From: xuxiaomeng <961592690@qq.com> Date: Mon, 23 May 2022 09:38:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00977.=E6=9C=89=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9=20Kotlin=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 24276bcf..9c06d8a3 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -359,7 +359,28 @@ class Solution { } ``` - +Kotlin: +```kotlin +class Solution { + // 双指针法 + fun sortedSquares(nums: IntArray): IntArray { + var res = IntArray(nums.size) + var left = 0 // 指向数组的最左端 + var right = nums.size - 1 // 指向数组端最右端 + // 选择平方数更大的那一个往 res 数组中倒序填充 + for (index in nums.size - 1 downTo 0) { + if (nums[left] * nums[left] > nums[right] * nums[right]) { + res[index] = nums[left] * nums[left] + left++ + } else { + res[index] = nums[right] * nums[right] + right-- + } + } + return res + } +} +``` -----------------------