Leetcode Note: Go - Sort Array by Parity

Sort Array By Parity - LeetCode
https://leetcode.com/problems/sort-array-by-parity/

  • Go 言語で取り組んだメモ

所感

  • int 配列 nums を指定して、配列先頭にある全ての偶数を移動し、その後に奇数を移動する

回答

Sort Array By Parity - LeetCode
https://leetcode.com/problems/sort-array-by-parity/solution/

Go Solution - LeetCode Discuss
https://leetcode.com/problems/sort-array-by-parity/discuss/804065/Go-Solution

func sortArrayByParity(A []int) []int {
    start := 0
    end := len(A) - 1
    
    for start < end {
        // odd
        if A[start] % 2 != 0 {
            // swap with end
            A[start], A[end] = A[end], A[start]
            end--
        } else {start++}
    }

    return A
}