From f8004f9b41bc011f8e961f3065dbab61f1f63a7d Mon Sep 17 00:00:00 2001 From: simonhancrew <597494370@qq.com> Date: Thu, 27 May 2021 15:58: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=20Python3=20Go=20?= =?UTF-8?q?Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 60 +++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 167a258c..b5d392e6 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -100,10 +100,66 @@ public: Java: 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 + else: + ans[k] = rm + j -= 1 + k -= 1 + return ans +``` Go: - +```Go +func sortedSquares(nums []int) []int { + n := len(nums) + i, j, k := 0, n-1, n-1 + ans := make([]int, n) + for i <= j { + lm, rm := nums[i]*nums[i], nums[j]*nums[j] + if lm > rm { + ans[k] = lm + i++ + } else { + ans[k] = rm + j-- + } + k-- + } + return ans +} +``` +Rust +``` +impl Solution { + pub fn sorted_squares(nums: Vec) -> Vec { + let n = nums.len(); + let (mut i,mut j,mut k) = (0,n - 1,n- 1); + let mut ans = vec![0;n]; + while i <= j{ + if nums[i] * nums[i] < nums[j] * nums[j] { + ans[k] = nums[j] * nums[j]; + j -= 1; + }else{ + ans[k] = nums[i] * nums[i]; + i += 1; + } + k -= 1; + } + ans + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)