From 082e3ae66e2c36508aadfc4fea58a32fbf8b803f Mon Sep 17 00:00:00 2001 From: Steve0x2a Date: Sun, 15 Aug 2021 13:58:49 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00922=E6=8C=89=E5=A5=87?= =?UTF-8?q?=E5=81=B6=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84II=20Python?= =?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/0922.按奇偶排序数组II.md | 27 +++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index 92db204d..97d7091e 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -149,7 +149,32 @@ class Solution { ## Python -```python +```python3 +#方法2 +class Solution: + def sortArrayByParityII(self, nums: List[int]) -> List[int]: + result = [0]*len(nums) + evenIndex = 0 + oddIndex = 1 + for i in range(len(nums)): + if nums[i] % 2: #奇数 + result[oddIndex] = nums[i] + oddIndex += 2 + else: #偶数 + result[evenIndex] = nums[i] + evenIndex += 2 + return result + +#方法3 +class Solution: + def sortArrayByParityII(self, nums: List[int]) -> List[int]: + oddIndex = 1 + for i in range(0,len(nums),2): #步长为2 + if nums[i] % 2: #偶数位遇到奇数 + while nums[oddIndex] % 2: #奇数位找偶数 + oddIndex += 2 + nums[i], nums[oddIndex] = nums[oddIndex], nums[i] + return nums ``` ## Go