Go/Leet Code
Array 101 Sort Array By Parity
Gopythor
2022. 3. 15. 01:45
728x90
반응형
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
- 1 <= nums.length <= 5000
- 0 <= nums[i] <= 5000
My code
func sortArrayByParity(nums []int) []int {
if len(nums) <= 1 {
return nums
}
lp := 0
rp := len(nums) - 1
for {
if lp >= rp {
break
}
if nums[lp]%2 == 0 {
lp++
} else {
nums[lp], nums[rp] = nums[rp], nums[lp]
}
if nums[rp]%2 != 0 {
rp--
} else {
nums[lp], nums[rp] = nums[rp], nums[lp]
}
}
return nums
}
https://go.dev/play/p/g2Ep4Is9nKW
- Just I implemented two pointers simply.
- I didn't know it will get 0ms runtime.
sample 0 ms submission
func sortArrayByParity(nums []int) []int {
index := -1
for i := 0; i < len(nums); i++ {
if nums[i] & 0x01 == 0 {
nums[i], nums[index + 1] = nums[index + 1], nums[i]
index++
}
}
return nums
}
- & 0x01 checks if nums[i] is odd or not.
- & is bitwise operation.
- if nums[i] is even, they start to swap each other.
- index array will have even, nums[i] will have odd.
- This code go until end of array.
Modification
func sortArrayByParity(nums []int) []int {
index := -1
for i := 0; i < len(nums); i++ {
if nums[i]&0001 == 0 {
nums[i], nums[index+1] = nums[index+1], nums[i]
index++
}
}
return nums
}
- This code also works becuase 0001 is also 1 as one.
sample 3 ms submission
func sortArrayByParity(A []int) []int {
j := 0
for i := range A {
if A[i] % 2 == 0 {
A[j], A[i] = A[i], A[j]
j++
}
}
return A
}
- simple code.
- It will be same with the former code.
sample 4 ms submission & sample 4700 KB submission
func sortArrayByParity(nums []int) []int {
hole := 0
for i, num := range nums {
if num % 2 == 0 {
if hole != i {
swap(nums, hole, i)
}
hole++
}
}
return nums
}
func swap(nums []int, i, j int) {
tmp := nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
- This is recorded less size submission.
- Looks complicated.
- hole is used write pointer.
- when hole is different with i, it will swap.
- Without hole if condition, also it works.
sample 4800 KB submission
func sortArrayByParity(nums []int) []int {
i, j := 0, len(nums)-1
for i < j {
if nums[i]%2 != 0 {
nums[i], nums[j] = nums[j], nums[i]
j--
} else {
i++
}
}
return nums
}
- It is two pointers.
sample 4900 KB submission
func sortArrayByParity(nums []int) []int {
p1, p2 := 0, len(nums)-1
for p1 != p2 && p1 < p2 {
if nums[p1] % 2 != 0 {
if nums[p2] % 2 == 0 {
temp := nums[p1]
nums[p1] = nums[p2]
nums[p2] = temp
p1++
p2--
} else {
p2--
}
} else {
p1++
}
}
return nums
}
- First if condition checks p1 is odd and p2 is even then they change.
- And they increase.
- If not p1 increase and p2 decrease.
- Looks complicated..
728x90
반응형