0922.按奇偶排序数组II , 增加golang实现

This commit is contained in:
yqq
2021-09-19 10:59:16 +08:00
parent 9b37c68aaf
commit d88ba0549b

View File

@ -11,6 +11,8 @@
# 922. 按奇偶排序数组II # 922. 按奇偶排序数组II
[力扣题目链接](https://leetcode-cn.com/problems/sort-array-by-parity-ii/)
给定一个非负整数数组 A A 中一半整数是奇数,一半整数是偶数。 给定一个非负整数数组 A A 中一半整数是奇数,一半整数是偶数。
对数组进行排序以便当 A[i] 为奇数时i 也是奇数 A[i] 为偶数时, i 也是偶数。 对数组进行排序以便当 A[i] 为奇数时i 也是奇数 A[i] 为偶数时, i 也是偶数。
@ -147,9 +149,9 @@ class Solution {
} }
``` ```
## Python ## Python3
```python3 ```python
#方法2 #方法2
class Solution: class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]: def sortArrayByParityII(self, nums: List[int]) -> List[int]:
@ -180,6 +182,28 @@ class Solution:
## Go ## Go
```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 ## JavaScript