From d88ba0549bc38f2e577d13a18d8bb606529426b1 Mon Sep 17 00:00:00 2001 From: yqq Date: Sun, 19 Sep 2021 10:59:16 +0800 Subject: [PATCH] =?UTF-8?q?0922.=E6=8C=89=E5=A5=87=E5=81=B6=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84II=20,=20=E5=A2=9E=E5=8A=A0golang?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0922.按奇偶排序数组II.md | 28 ++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index 97d7091e..5b66247e 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -11,6 +11,8 @@ # 922. 按奇偶排序数组II +[力扣题目链接](https://leetcode-cn.com/problems/sort-array-by-parity-ii/) + 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。 @@ -147,9 +149,9 @@ class Solution { } ``` -## Python +## Python3 -```python3 +```python #方法2 class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: @@ -180,6 +182,28 @@ class Solution: ## Go ```go + +// 方法一 +func sortArrayByParityII(nums []int) []int { + // 分别存放 nums 中的奇数、偶数 + even, odd := []int{}, []int{} + for i := 0; i < len(nums); i++ { + if (nums[i] % 2 == 0) { + even = append(even, nums[i]) + } else { + odd = append(odd, nums[i]) + } + } + + // 把奇偶数组重新存回 nums + result := make([]int, len(nums)) + index := 0 + for i := 0; i < len(even); i++ { + result[index] = even[i]; index++; + result[index] = odd[i]; index++; + } + return result; +} ``` ## JavaScript