-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort-array-by-parity.go
53 lines (45 loc) · 1011 Bytes
/
sort-array-by-parity.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"fmt"
)
// source: https://leetcode.com/problems/sort-array-by-parity/
func sortArrayByParity(nums []int) []int {
index := 0
for i, v := range nums {
if v%2 == 0 {
nums[index], nums[i] = nums[i], nums[index]
index++
}
}
return nums
}
func sortArrayByParity_(nums []int) []int {
var odd, even = make([]int, 0, len(nums)), make([]int, 0, len(nums))
for i := range nums {
if nums[i]%2 == 0 {
even = append(even, nums[i])
} else {
odd = append(odd, nums[i])
}
}
return append(even, odd...)
}
func sortArrayByParity__(nums []int) []int {
var res = make([]int, 0, len(nums))
for i := range nums {
if nums[i]%2 == 0 {
res = append([]int{nums[i]}, res...)
} else {
res = append(res, nums[i])
}
}
return res
}
func main() {
// Example 1
var nums1 = []int{3, 1, 2, 4}
fmt.Println("Expected: [2,4,3,1] Output: ", sortArrayByParity(nums1))
// Example 2
var nums2 = []int{0}
fmt.Println("Expected: [0] Output: ", sortArrayByParity(nums2))
}