From 934dd4e3131485802edd5d7c45fd60dd4f8f2827 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 15:19:23 -0500 Subject: [PATCH] =?UTF-8?q?Update=200977.=E6=9C=89=E5=BA=8F=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 41 ++++++++++++++++++-------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 57f8de02..4fbdd1cd 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -140,22 +140,37 @@ class Solution { Python: ```Python +(版本一)双指针法 class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: - n = len(nums) - i,j,k = 0,n - 1,n - 1 - ans = [-1] * n - while i <= j: - lm = nums[i] ** 2 - rm = nums[j] ** 2 - if lm > rm: - ans[k] = lm - i += 1 + l, r, i = 0, len(nums)-1, len(nums)-1 + res = [float('inf')] * len(nums) # 需要提前定义列表,存放结果 + while l <= r: + if nums[l] ** 2 < nums[r] ** 2: # 左右边界进行对比,找出最大值 + res[i] = nums[r] ** 2 + r -= 1 # 右指针往左移动 else: - ans[k] = rm - j -= 1 - k -= 1 - return ans + res[i] = nums[l] ** 2 + l += 1 # 左指针往右移动 + i -= 1 # 存放结果的指针需要往前平移一位 + return res +``` + +```Python +(版本二)暴力排序法 +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + for i in range(len(nums)): + nums[i] *= nums[i] + nums.sort() + return nums +``` + +```Python +(版本三)暴力排序法+列表推导法 +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + return sorted(x*x for x in nums) ``` Go: