mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
0922.按奇偶排序数组II , 增加golang实现
This commit is contained in:
@ -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
|
||||||
|
Reference in New Issue
Block a user