Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 5618d85

Browse files
committed
9058 finish
1 parent 5e5eca9 commit 5618d85

File tree

3 files changed

+110
-0
lines changed

3 files changed

+110
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# [905. Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)
2+
3+
## 题目
4+
5+
Given an array `A` of non-negative integers, return an array consisting of all the even elements of `A`, followed by all the odd elements of `A`.
6+
7+
You may return any answer array that satisfies this condition.
8+
9+
Example 1:
10+
11+
```text
12+
Input: [3,1,2,4]
13+
Output: [2,4,3,1]
14+
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
15+
```
16+
17+
Note:
18+
19+
- 1 <= A.length <= 5000
20+
- 0 <= A[i] <= 5000
21+
22+
## 解题思路
23+
24+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package problem0905
2+
3+
func sortArrayByParity(a []int) []int {
4+
i, j, size := 0, len(a)-1, len(a)
5+
for i < j {
6+
for i < size && a[i]%2 == 0 {
7+
i++
8+
}
9+
for i < j && a[j]%2 == 1 {
10+
j--
11+
}
12+
if i < j {
13+
a[i], a[j] = a[j], a[i]
14+
}
15+
}
16+
return a
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package problem0905
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
A []int
13+
}{
14+
15+
{
16+
[]int{3, 1, 2, 4},
17+
},
18+
19+
// 可以有多个 testcase
20+
}
21+
22+
func split(a []int) (evens, odds []int) {
23+
size := len(a)
24+
var i int
25+
for i = 0; i < size; i++ {
26+
if a[i]%2 == 1 {
27+
break
28+
}
29+
}
30+
return a[:i], a[i:]
31+
}
32+
33+
func isAllEven(a []int) bool {
34+
for _, n := range a {
35+
if n%2 == 1 {
36+
return false
37+
}
38+
}
39+
return true
40+
}
41+
42+
func isAllOdd(a []int) bool {
43+
for _, n := range a {
44+
if n%2 == 0 {
45+
return false
46+
}
47+
}
48+
return true
49+
}
50+
51+
func Test_sortArrayByParity(t *testing.T) {
52+
ast := assert.New(t)
53+
54+
for _, tc := range tcs {
55+
fmt.Printf("~~%v~~\n", tc)
56+
ans := sortArrayByParity(tc.A)
57+
evens, odds := split(ans)
58+
ast.True(isAllEven(evens))
59+
ast.True(isAllOdd(odds))
60+
}
61+
}
62+
63+
func Benchmark_sortArrayByParity(b *testing.B) {
64+
for i := 0; i < b.N; i++ {
65+
for _, tc := range tcs {
66+
sortArrayByParity(tc.A)
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)