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 + } +} +``` -----------------------